C#におけるStreamとByte[]の相互変換
1、バイナリをピクチャに変換
2,C#中byte[]とstringの変換コード
2.1
2.2
3,C#Streamとbyte[]間の変換
4,Streamとファイル間の変換Streamをファイルに書き込む
5,ファイルからStreamを読み込む
6,BitmapをByte[]に変換
回転:http://www.ibcibc.com/thread-4162-1-4.html
MemoryStream ms = new MemoryStream(bytes);
ms.Position = 0;
Image img = Image.FromStream(ms);
ms.Close();
this.pictureBox1.Image
2,C#中byte[]とstringの変換コード
2.1
System.Text.UnicodeEncoding converter = new System.Text.UnicodeEncoding();
byte[] inputBytes =converter.GetBytes(inputString);
string inputString = converter.GetString(inputBytes);
2.2
string inputString = System.Convert.ToBase64String(inputBytes);
byte[] inputBytes = System.Convert.FromBase64String(inputString);
FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
3,C#Streamとbyte[]間の変換
/// 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;
}
/// byte[] Stream
public Stream BytesToStream(byte[] bytes)
{
Stream stream = new MemoryStream(bytes);
return stream;
}
4,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();
}
5,ファイルから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;
}
6,BitmapをByte[]に変換
Bitmap BitReturn = new Bitmap();
byte[] bReturn = null;
MemoryStream ms = new MemoryStream();
BitReturn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
bReturn = ms.GetBuffer();
回転:http://www.ibcibc.com/thread-4162-1-4.html