Stream转Byte数组、Image转Byte数组、文件转Stream等
////// 将 Stream 转成 byte[]/// /// ///public static byte[] StreamToBytes(Stream stream){ byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); // 设置当前流的位置为流的开始 stream.Seek(0, SeekOrigin.Begin); return bytes;}/// /// 将 byte[] 转成 Stream/// /// ///public static Stream BytesToStream(byte[] bytes){ Stream stream = new MemoryStream(bytes); return stream;}/// /// 字节流转换成图片 /// /// 要转换的字节流 ///转换得到的Image对象 public static Image BytToImg(byte[] byt){ try { MemoryStream ms = new MemoryStream(byt); Image img = Image.FromStream(ms); return img; } catch (Exception ex) { LogHelper.WriteError("StreamHelper.BytToImg 异常", ex); return null; }}////// 图片转换成字节流 /// /// ///public static byte[] ImageToByteArray(Image img){ ImageConverter imgconv = new ImageConverter(); byte[] b = (byte[])imgconv.ConvertTo(img, typeof(byte[])); return b;}/// /// 把图片Url转化成Image对象/// /// ///public static Image Url2Img(string imageUrl){ try { if (string.IsNullOrEmpty(imageUrl)) { return null; } WebRequest webreq = WebRequest.Create(imageUrl); WebResponse webres = webreq.GetResponse(); Stream stream = webres.GetResponseStream(); Image image; image = Image.FromStream(stream); stream.Close(); return image; } catch (Exception ex) { LogHelper.WriteError("StreamHelper.Url2Img 异常", ex); } return null;}/// /// 把本地图片路径转成Image对象/// /// ///public static Image ImagePath2Img(string imagePath){ try { if (string.IsNullOrEmpty(imagePath)) { return null; } byte[] bytes = Image2ByteWithPath(imagePath); Image image = BytToImg(bytes); return image; } catch (Exception ex) { LogHelper.WriteError("StreamHelper.ImagePath2Img 异常", ex); return null; }}
详细代码看