程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> Stream/Bytes[]/Image對象相互轉化,streambytes

Stream/Bytes[]/Image對象相互轉化,streambytes

編輯:C#入門知識

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/ 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved