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>
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>
Comparison of methods:
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!