C#實現(xiàn)Stream與byte[]之間的轉換實例教程
本文以實例形式詳細介紹了C#實現(xiàn)Stream與byte[]之間的轉換的方法,分享給大家供大家參考之用。具體方法如下:
一、二進制轉換成圖片
MemoryStream ms = new MemoryStream(bytes); ms.Position = 0; Image img = Image.FromStream(ms); ms.Close(); this.pictureBox1.Image
二、C#中byte[]與string的轉換代碼
1.
System.Text.UnicodeEncoding converter = new System.Text.UnicodeEncoding(); byte[] inputBytes =converter.GetBytes(inputString); string inputString = converter.GetString(inputBytes);
2.
string inputString = System.Convert.ToBase64String(inputBytes); byte[] inputBytes = System.Convert.FromBase64String(inputString); FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
三、C# Stream 和 byte[] 之間的轉換
1.將 Stream 轉成 byte[]
public byte[] StreamToBytes(Stream stream)
{
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
// 設置當前流的位置為流的開始
stream.Seek(0, SeekOrigin.Begin);
return bytes;
}
2.將 byte[] 轉成 Stream
public Stream BytesToStream(byte[] bytes)
{
Stream stream = new MemoryStream(bytes);
return stream;
}
四、Stream 和 文件之間的轉換
將 Stream 寫入文件
public void StreamToFile(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();
}
五、從文件讀取 Stream
public Stream FileToStream(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[] 轉換成 Stream
Stream stream = new MemoryStream(bytes);
return stream;
}
六、Bitmap 轉化為 Byte[]
Bitmap BitReturn = new Bitmap(); byte[] bReturn = null; MemoryStream ms = new MemoryStream(); BitReturn.Save(ms, System.Drawing.Imaging.ImageFormat.Png); bReturn = ms.GetBuffer();
相信本文所述對大家的C#程序設計有一定的借鑒價值。
相關文章
C# ManagementObjectSearcher操作window案例詳解
這篇文章主要介紹了C# ManagementObjectSearcher操作window案例詳解,本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內容,需要的朋友可以參考下2021-08-08
C#使用ADO.Net連接數(shù)據庫與DbProviderFactory實現(xiàn)多數(shù)據庫訪問
這篇文章介紹了C#使用ADO.Net連接數(shù)據庫與DbProviderFactory實現(xiàn)多數(shù)據庫訪問的方法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-05-05
C# WinForm調用Shell_NotifyIcon的示例代碼
這篇文章主要介紹了C# WinForm調用Shell_NotifyIcon的示例代碼,幫助大家更好的理解和使用c#,感興趣的朋友可以了解下2020-11-11
C# TabControl控件中TabPage選項卡切換時的觸發(fā)事件問題
這篇文章主要介紹了C# TabControl控件中TabPage選項卡切換時的觸發(fā)事件問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04
C#操作Clipboard讀取剪切板中數(shù)據實例詳解
這篇文章主要介紹了C#操作Clipboard讀取剪切板中數(shù)據的方法,實例分析了C#讀取剪貼板數(shù)據的具體步驟與實現(xiàn)技巧,需要的朋友可以參考下2015-05-05

