Home > Backend Development > C++ > How to Convert Images to Byte Arrays and Back?

How to Convert Images to Byte Arrays and Back?

Patricia Arquette
Release: 2025-01-26 03:31:10
Original
926 people have browsed it

How to Convert Images to Byte Arrays and Back?

Conversion between image and byte array

Question: How to convert an image to a byte array, and how to convert a byte array back to an image?

Answer:

To convert an image to a byte array, you can use the following sample code:

<code class="language-csharp">public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
    using (var ms = new MemoryStream())
    {
        imageIn.Save(ms, imageIn.RawFormat);
        return ms.ToArray();
    }
}</code>
Copy after login

This code uses MemoryStream to store the image and then converts it to a byte array.

To convert the byte array back to an image, you can also use a class like this:

<code class="language-csharp">public class ImageConverter
{
    public ImageConverter() { }

    public Image ByteToImage(byte[] byteArrayIn)
    {
        using (var ms = new MemoryStream(byteArrayIn))
        {
            Image returnImage = Image.FromStream(ms);
            return returnImage;
        }
    }

    public byte[] ImageToByte(Image imageIn)
    {
        using (var ms = new MemoryStream())
        {
            imageIn.Save(ms, ImageFormat.Png); // 指定保存格式为PNG
            return ms.ToArray();
        }
    }
}</code>
Copy after login

This code provides a more structured way to perform conversion between images and byte arrays, and explicitly specifies the format in which the image is saved as PNG. You can modify ImageFormat to choose a different format, such as JPEG or GIF, if needed.

The above is the detailed content of How to Convert Images to Byte Arrays and Back?. 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