把获得的数据流转换成一副图片
其原理就是把获得倒的数据流序列化到内存中,然后经过加工,在把数据从内存中反序列化出来就行了。
难点就是在如何实现加工。因为Bitmap有一个专有的格式,我们常称这个格式为数据头。加工的过程就是要把这个数据头与我们之前获得的数据流合并起来。(也就是要把这个头加入到我们之前获得的数据流的前面)
那么这个头是什么呢?它是一个固定长度(14个byte)的数据。具体内容见代码。由于这个头是对任何Bitmap对象都是通用的,所以加入头的过程基本上都是一样的。代码如下:
1usingSystem;
2usingSystem.Collections.Generic;
3usingSystem.Linq;
4usingSystem.Text;
5usingSystem.Drawing;
6usingSystem.IO;
7
8public BitmapAddHeader(byte[]imageDataDetails)
9 {
10 Bitmapbitmap=null;
11 intlength=imageDataDetails.GetLength(0);
12 using(MemoryStreamstream=newMemoryStream(length+14))//为头腾出14个长度的空间
13 {
14 byte[]buffer=newbyte[13];
15 buffer[0]=0x42;//Bitmap固定常数
16 buffer[1]=0x4d;//Bitmap固定常数
17 stream.Write(buffer,0,2);//先写入头的前两个字节
18
19 //把我们之前获得的数据流的长度转换成字节,
20 //这个是用来告诉“头”我们的实际图像数据有多大
21 byte[]bytes=BitConverter.GetBytes(length);
22 stream.Write(bytes,0,4);//把这个长度写入头中去
23 buffer[0]=0;
24 buffer[1]=0;
25 buffer[2]=0;
26 buffer[3]=0;
27 stream.Write(buffer,0,4);//在写入4个字节长度的数据到头中去
28 intnum2=0x36;//Bitmap固定常数
29 bytes=BitConverter.GetBytes(num2);
30 stream.Write(bytes,0,4);//在写入最后4个字节的长度
31 stream.GetBuffer();
32 stream.Write(imageDataDetails,0,length);//把实际的图像数据全部追加到头的后面
33 bitmap=newBitmap(stream);//用内存流构造出一幅bitmap的图片
34 bitmap.RotateFlip(RotateFlipType.Rotate180FlipX);
35 stream.Close();
36 returnbitmap;//最后就得到了我们想要的图片了
37 }
38 }
那么反过来怎么实现呢?