Home > Backend Development > C++ > How to Efficiently Convert a Windows Bitmap to a Byte Array?

How to Efficiently Convert a Windows Bitmap to a Byte Array?

Barbara Streisand
Release: 2025-01-23 15:12:11
Original
945 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template