C # Bitmap types and byte[] types convert to each other

Source: Internet
Author: User
Bitmap => byte[] Bitmap b = new Bitmap ("Test.bmp");
MemoryStream ms = new MemoryStream ();
B.save (ms,system.drawing.imaging.imageformat.bmp);
Byte[] bytes= Ms.  GetBuffer (); Byte[] bytes= Ms. ToArray (); These two sentences can be, as for the difference, there are explanations below
Ms. Close ();

Byte[] => Bitmap
Byte[] bytelist=bytes;
MemoryStream ms1 = new MemoryStream (bytelist);
Bitmap BM = (Bitmap) image.fromstream (MS1);
Ms1. Close ();


1, because if you do not use BMP to convert bytes, the conversion to bytes will lose data;
2. The MemoryStream GetBuffer does not get the content stored by this stream, but rather returns the underlying byte array of the stream, possibly including some bytes not used at the time of expansion.
If you use the MemoryStream, you can not say that the effect is similar. Because I have memorystream this class in Java, so the issues like this and should be noted are basically clear, and GetBuffer is that there are many people who think that this is the way to get the bytes written to MemoryStream, but that's not the case. Because MemoryStream uses byte[] to store data, there is an extended process when the data is written, which means that the length of the stream is not the length of its byte[] field. And GetBuffer return is byte[] this field.
Here's a partial implementation of the GetBuffer, and maybe you'll see this more clearly:
Public byte[] GetBuffer () {
return this._buffer;
}
Here's how to implement the ToArray:
Public byte[] ToArray () {
Byte[] bs = new Byte[this._length-this._origin];
for (int i = this._origin, j = 0;   i < this._length; i++)
Bs[j++] = This._buffer[i];
return BS;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.