欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#實(shí)現(xiàn)Stream與byte[]之間的轉(zhuǎn)換實(shí)例教程

 更新時(shí)間:2014年09月01日 10:25:14   投稿:shichen2014  
這篇文章主要介紹了C#實(shí)現(xiàn)Stream與byte[]之間的轉(zhuǎn)換方法,具體講解了二進(jìn)制轉(zhuǎn)換成圖片、byte[]與string的轉(zhuǎn)換、Stream 和 byte[] 之間的轉(zhuǎn)換、Stream 和 文件之間的轉(zhuǎn)換、從文件讀取 Stream以及Bitmap 轉(zhuǎn)化為 Byte[]等,需要的朋友可以參考下

本文以實(shí)例形式詳細(xì)介紹了C#實(shí)現(xiàn)Stream與byte[]之間的轉(zhuǎn)換的方法,分享給大家供大家參考之用。具體方法如下:

一、二進(jìn)制轉(zhuǎn)換成圖片

MemoryStream ms = new MemoryStream(bytes); 
ms.Position = 0; 
Image img = Image.FromStream(ms); 
ms.Close(); 
this.pictureBox1.Image

二、C#中byte[]與string的轉(zhuǎn)換代碼

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[] 之間的轉(zhuǎn)換

1.將 Stream 轉(zhuǎn)成 byte[] 

public byte[] StreamToBytes(Stream stream) 
{ 
  byte[] bytes = new byte[stream.Length]; 
  stream.Read(bytes, 0, bytes.Length); 
  // 設(shè)置當(dāng)前流的位置為流的開(kāi)始 
  stream.Seek(0, SeekOrigin.Begin); 
  return bytes; 
} 

2.將 byte[] 轉(zhuǎn)成 Stream 

public Stream BytesToStream(byte[] bytes) 
{ 
  Stream stream = new MemoryStream(bytes); 
  return stream; 
}

四、Stream 和 文件之間的轉(zhuǎn)換

將 Stream 寫(xiě)入文件

public void StreamToFile(Stream stream,string fileName) 
{ 
  // 把 Stream 轉(zhuǎn)換成 byte[] 
  byte[] bytes = new byte[stream.Length]; 
  stream.Read(bytes, 0, bytes.Length); 
  // 設(shè)置當(dāng)前流的位置為流的開(kāi)始 
  stream.Seek(0, SeekOrigin.Begin); 
  // 把 byte[] 寫(xiě)入文件 
  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) 
{       
  // 打開(kāi)文件 
  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[] 轉(zhuǎn)換成 Stream 
  Stream stream = new MemoryStream(bytes); 
  return stream; 
}

六、Bitmap 轉(zhuǎn)化為 Byte[]

Bitmap BitReturn = new Bitmap(); 
byte[] bReturn = null; 
MemoryStream ms = new MemoryStream(); 
BitReturn.Save(ms, System.Drawing.Imaging.ImageFormat.Png); 
bReturn = ms.GetBuffer();

相信本文所述對(duì)大家的C#程序設(shè)計(jì)有一定的借鑒價(jià)值。

相關(guān)文章

最新評(píng)論