Efficient bitmap to byte array conversion in C#
Saving a Windows bitmap to a temporary file and then reading it as a byte array is a common conversion method, but it is not efficient. Here are two alternatives in C# that offer better performance.
Use ImageConverter
The ImageConverter class provides a convenient way to convert an image into a byte array:
<code class="language-csharp">public static byte[] ImageToByte(Image img) { ImageConverter converter = new ImageConverter(); return (byte[])converter.ConvertTo(img, typeof(byte[])); }</code>
This method does not require extensive coding and is ideal for smaller conversion tasks.
Use MemoryStream
The MemoryStream class allows you to save images to memory instead of disk:
<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>
Additional advantages of this method are the choice of image format and the option to save the data to disk or keep it in memory.
These alternatives provide efficient and flexible solutions for converting bitmaps to byte arrays, reducing unnecessary disk operations and improving performance.
The above is the detailed content of How Can I Efficiently Convert a Bitmap to a Byte Array in C#?. For more information, please follow other related articles on the PHP Chinese website!