Riya
Riya

Reputation: 559

conversion of image to byte array

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

Upvotes: 11

Views: 18003

Answers (6)

Neon Blue
Neon Blue

Reputation: 391

Based off of MusiGenesis; helped me a lot but I had many image types. This will save any image type that it can read.

            System.Drawing.Imaging.ImageFormat ImageFormat = imageToConvert.RawFormat;
        byte[] Ret;
        try
        {
            using (MemoryStream ms = new MemoryStream())
            {
                imageToConvert.Save(ms, ImageFormat);
                Ret = ms.ToArray();
            }
        }
        catch (Exception) { throw; }
        return Ret;

Upvotes: 0

Cocowalla
Cocowalla

Reputation: 14350

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.

Upvotes: 6

MusiGenesis
MusiGenesis

Reputation: 75376

If your image is already in the form of a System.Drawing.Image, then you can do something like this:

public byte[] convertImageToByteArray(System.Drawing.Image image)
{
     using (MemoryStream ms = new MemoryStream())
     {
         image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); 
             // or whatever output format you like
         return ms.ToArray(); 
     }
}

You would use this function with the image in your picture box control like this:

byte[] imageBytes = convertImageToByteArray(pictureBox1.Image);

Upvotes: 6

santosh singh
santosh singh

Reputation: 28672

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[]));
}

Upvotes: 12

Shekhar_Pro
Shekhar_Pro

Reputation: 18430

You can use File.ReadAllBytes method to get bytes

If you are using FileUpload class then you can use FileBytes Property to get the Bytes as Byte Array.

Upvotes: -1

Alex Pacurar
Alex Pacurar

Reputation: 5871

to get the bytes from any file try:

byte[] bytes =  File.ReadAllBytes(pathToFile);

Upvotes: 0

Related Questions