c#中字节数组byte[]、图片image、流stream,字符串string、内存流MemoryStream、文件file,之间的转换
生活随笔
收集整理的這篇文章主要介紹了
c#中字节数组byte[]、图片image、流stream,字符串string、内存流MemoryStream、文件file,之间的转换
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
字節數組byte[]與圖片image之間的轉化
字節數組轉換成圖片
public static Image byte2img(byte[] buffer) {MemoryStream ms = new MemoryStream(buffer);ms.Position = 0;Image img = Image.FromStream(ms);ms.Close();return img; }- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
圖片轉化為字節數組
public static byte[] byte2img(Bitmap Bit) {byte[] back = null;MemoryStream ms = new MemoryStream();Bit.Save(ms, System.Drawing.Imaging.ImageFormat.Png);back = ms.GetBuffer();return back; }- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
字節數組byte[]與字符串string之間的編碼解碼
字符串到字節數組的編碼
public static byte[] str2byte(string str) {byte[] data = System.Text.Encoding.UTF8.GetBytes(param);//byte[] data = Convert.FromBase64String(param);//有很多種編碼方式,可參考:http://blog.csdn.net/luanpeng825485697/article/details/77622243return data; }- 1
- 2
- 3
- 4
- 5
- 6
- 7
字節數組到字符串的解碼
public static string str2byte(byte[] data) {string str = System.Text.Encoding.UTF8.GetString(data);//str = Convert.ToBase64String(data);//有很多種編碼方式,可參考:http://blog.csdn.net/luanpeng825485697/article/details/77622243return str; }- 1
- 2
- 3
- 4
- 5
- 6
- 7
字節數組byte[]與內存流MemoryStream之間的轉換
字節數組轉化為輸入內存流
public static MemoryStream byte2stream(byte[] data) {MemoryStream inputStream = new MemoryStream(data);return inputStream; }- 1
- 2
- 3
- 4
- 5
輸出內存流轉化為字節數組
public static byte[] byte2stream(MemoryStream outStream) {return outStream.ToArray(); }- 1
- 2
- 3
- 4
字節數組byte[]與流stream之間的轉換
將 Stream 轉成 byte[]
public byte[] stream2byte(Stream stream) {byte[] bytes = new byte[stream.Length];stream.Read(bytes, 0, bytes.Length);// 設置當前流的位置為流的開始stream.Seek(0, SeekOrigin.Begin);return bytes; }- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
將 byte[] 轉成 Stream
public Stream byte2stream(byte[] bytes) {Stream stream = new MemoryStream(bytes);return stream; }- 1
- 2
- 3
- 4
- 5
流Stream 和 文件file之間的轉換
將 Stream 寫入文件
public void stream2file(Stream stream,string fileName) {// 把 Stream 轉換成 byte[]byte[] bytes = new byte[stream.Length];stream.Read(bytes, 0, bytes.Length);// 設置當前流的位置為流的開始stream.Seek(0, SeekOrigin.Begin);// 把 byte[] 寫入文件FileStream fs = new FileStream(fileName, FileMode.Create);BinaryWriter bw = new BinaryWriter(fs);bw.Write(bytes);bw.Close();fs.Close(); }- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
從文件讀取 Stream
public Stream file2stream(string fileName) { // 打開文件FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);// 讀取文件的 byte[]byte[] bytes = new byte[fileStream.Length];fileStream.Read(bytes, 0, bytes.Length);fileStream.Close();// 把 byte[] 轉換成 StreamStream stream = new MemoryStream(bytes);return stream; }- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
總結
以上是生活随笔為你收集整理的c#中字节数组byte[]、图片image、流stream,字符串string、内存流MemoryStream、文件file,之间的转换的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: H264基本概念之 宏块、片和片组
- 下一篇: String到底是值类型还是引用类型(C