C#实现Stream与byte[]之间的转换实例教程
本文以实例形式详细介绍了C#实现Stream与byte[]之间的转换的方法,分享给大家供大家参考之用。具体方法如下:
一、二进制转换成图片
MemoryStreamms=newMemoryStream(bytes); ms.Position=0; Imageimg=Image.FromStream(ms); ms.Close(); this.pictureBox1.Image
二、C#中byte[]与string的转换代码
1.
System.Text.UnicodeEncodingconverter=newSystem.Text.UnicodeEncoding(); byte[]inputBytes=converter.GetBytes(inputString); stringinputString=converter.GetString(inputBytes);
2.
stringinputString=System.Convert.ToBase64String(inputBytes); byte[]inputBytes=System.Convert.FromBase64String(inputString); FileStreamfileStream=newFileStream(fileName,FileMode.Open,FileAccess.Read,FileShare.Read);
三、C#Stream和byte[]之间的转换
1.将Stream转成byte[]
publicbyte[]StreamToBytes(Streamstream) { byte[]bytes=newbyte[stream.Length]; stream.Read(bytes,0,bytes.Length); //设置当前流的位置为流的开始 stream.Seek(0,SeekOrigin.Begin); returnbytes; }
2.将byte[]转成Stream
publicStreamBytesToStream(byte[]bytes) { Streamstream=newMemoryStream(bytes); returnstream; }
四、Stream和文件之间的转换
将Stream写入文件
publicvoidStreamToFile(Streamstream,stringfileName) { //把Stream转换成byte[] byte[]bytes=newbyte[stream.Length]; stream.Read(bytes,0,bytes.Length); //设置当前流的位置为流的开始 stream.Seek(0,SeekOrigin.Begin); //把byte[]写入文件 FileStreamfs=newFileStream(fileName,FileMode.Create); BinaryWriterbw=newBinaryWriter(fs); bw.Write(bytes); bw.Close(); fs.Close(); }
五、从文件读取Stream
publicStreamFileToStream(stringfileName) { //打开文件 FileStreamfileStream=newFileStream(fileName,FileMode.Open,FileAccess.Read,FileShare.Read); //读取文件的byte[] byte[]bytes=newbyte[fileStream.Length]; fileStream.Read(bytes,0,bytes.Length); fileStream.Close(); //把byte[]转换成Stream Streamstream=newMemoryStream(bytes); returnstream; }
六、Bitmap转化为Byte[]
BitmapBitReturn=newBitmap(); byte[]bReturn=null; MemoryStreamms=newMemoryStream(); BitReturn.Save(ms,System.Drawing.Imaging.ImageFormat.Png); bReturn=ms.GetBuffer();
相信本文所述对大家的C#程序设计有一定的借鉴价值。