If you want to convert an Image to a byte array in C#, you can use the following extension method:

 

[TestMethod]
public void Test()
{
    Image image = null; // Supply your image here.
    byte[] bytes = image.ToBytes();
}
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace Services.Extensions
{
    /// <summary>
    /// Extensions to the [System.Drawing.Image] class
    /// </summary>
    public static class ImageExtensions
    {
        /// <summary>
        /// Converts an image to an array of bytes.
        /// </summary>
        /// <param name="image">The image.</param>
        /// <returns></returns>
        public static byte[] ToBytes(this Image image)
        {
            byte[] result = null;
            using (var stream = new MemoryStream())
            {
                image.Save(stream, image.RawFormat as ImageFormat);
                result = stream.ToArray();
            }
            return result;
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.