Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conversion of image to byte array

Tags:

c#

.net

Can anyone please tell me how an image(.jpg,.gif,.bmp) is converted into a byte array ?

like image 221
Riya Avatar asked Feb 19 '11 13:02

Riya


2 Answers

The easiest way to convert an image to bytes is to use the ImageConverter class under the System.Drawing namespace

public static byte[] ImageToByte(Image img)
{
    ImageConverter converter = new ImageConverter();
    return (byte[])converter.ConvertTo(img, typeof(byte[]));
}
like image 129
santosh singh Avatar answered Sep 21 '22 12:09

santosh singh


I've assumed what you want is the pixel values. Assuming bitmap is a System.Windows.Media.Imaging.BitmapSource:

int stride = bitmap.PixelWidth * ((bitmap.Format.BitsPerPixel + 7) / 8);
byte[] bmpPixels = new byte[bitmap.PixelHeight * stride];
bitmap.CopyPixels(bmpPixels, stride, 0);

Note that the 'stride' is the number of bytes required for each row of pixel ddata. Some more explanation available here.

like image 22
Cocowalla Avatar answered Sep 23 '22 12:09

Cocowalla