Home >Backend Development >C++ >How to Efficiently Convert a Windows Bitmap to a Byte Array?
Convert Windows bitmap to byte array
Converting Windows bitmap to byte array is a common task in various applications. While saving the image to a temporary file and then using a FileStream to read its contents is a viable approach, there is a more efficient and general approach.
ImageConverter class
A convenient way is to use the ImageConverter class:
<code class="language-c#">public static byte[] ImageToByte(Image img) { ImageConverter converter = new ImageConverter(); return (byte[])converter.ConvertTo(img, typeof(byte[])); }</code>
This method easily converts an image to a byte array without additional coding.
MemoryStream
Another way is to use memory streams:
<code class="language-c#">public static byte[] ImageToByte2(Image img) { using (var stream = new MemoryStream()) { img.Save(stream, System.Drawing.Imaging.ImageFormat.Png); return stream.ToArray(); } }</code>
This method simulates the temporary file method, but instead of saving the image to disk, it stores it in memory. This provides flexibility, allowing you to choose to save to memory or disk depending on your needs.
The above is the detailed content of How to Efficiently Convert a Windows Bitmap to a Byte Array?. For more information, please follow other related articles on the PHP Chinese website!