Stream/Bytes[]/Image對象相互轉化,streambytes
Stream/Bytes[]/Image對象相互轉化
Stream轉Byte數組、Image轉Byte數組、文件轉Stream等


![]()
/// <summary>
/// 將 Stream 轉成 byte[]
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
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;
}
將 Stream 轉成 byte[]

![]()
/// <summary>
/// 將 byte[] 轉成 Stream
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static Stream BytesToStream(byte[] bytes)
{
Stream stream = new MemoryStream(bytes);
return stream;
}
byte[] 轉成 Stream

![]()
// <summary>
/// 字節流轉換成圖片
/// </summary>
/// <param name="byt">要轉換的字節流</param>
/// <returns>轉換得到的Image對象</returns>
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;
}
}
字節流轉換成圖片

![]()
/// <summary>
/// 圖片轉換成字節流
/// </summary>
/// <param name="img"></param>
/// <returns></returns>
public static byte[] ImageToByteArray(Image img)
{
ImageConverter imgconv = new ImageConverter();
byte[] b = (byte[])imgconv.ConvertTo(img, typeof(byte[]));
return b;
}
圖片轉換成字節流

![]()
/// <summary>
/// 把圖片Url轉化成Image對象
/// </summary>
/// <param name="imageUrl"></param>
/// <returns></returns>
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;
}
把圖片Url轉化成Image對象

![]()
/// <summary>
/// 把本地圖片路徑轉成Image對象
/// </summary>
/// <param name="imagePath"></param>
/// <returns></returns>
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;
}
}
把圖片Url轉化成Image對象
轉自:
作者:樊勇
出處:http://www.cnblogs.com/fanyong/