Home > Backend Development > C++ > What's the Most Efficient Way to Convert a Bitmap to a Byte Array in C#?

What's the Most Efficient Way to Convert a Bitmap to a Byte Array in C#?

Patricia Arquette
Release: 2025-01-23 14:52:09
Original
953 people have browsed it

What's the Most Efficient Way to Convert a Bitmap to a Byte Array in C#?

Several ways to efficiently convert C# Bitmap to byte array

Convert Bitmap to byte array. Although the FileStream method is common and easy to understand, the efficiency is not optimal. Here are two more efficient methods:

1. Use ImageConverter:

<code class="language-csharp">public static byte[] ImageToByte(Image img)
{
    ImageConverter converter = new ImageConverter();
    return (byte[])converter.ConvertTo(img, typeof(byte[]));
}</code>
Copy after login

2. Use MemoryStream:

<code class="language-csharp">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

Comparison of methods:

  • ImageConverter: The code is simple and easy to use.
  • MemoryStream: Supports custom image formats and saves them directly to memory without disk operation.

Both methods are faster and more efficient than the FileStream method. Which method to choose depends on the needs of the specific application scenario.

The above is the detailed content of What's the Most Efficient Way to Convert a Bitmap to a Byte Array in C#?. 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