Convert Image to Byte Array

As the subject says ... if you want to convert an Image to an array of bytes to save it in the database or in a file or send it to a web service or another application , just put the following extension method in a static class and call it from the Image object like :

byte[] mImageBytes = img.ToBytes(ImageFormat.Png);

public static byte[] ToBytes(this Image image, ImageFormat format)
{
    if (image == null)
       throw new ArgumentNullException("image");
    if (format == null)
       throw new ArgumentNullException("format");
 
    using (MemoryStream stream = new MemoryStream())
    {
       image.Save(stream, format);
       return stream.ToArray();
    }
}


No comments:

Post a Comment