Can anyone please tell me how an image(.jpg,.gif,.bmp) is converted into a byte array ?
-
Where do you have your image? In a file or in an Image object or some Stream?Albin Sunnanbo– Albin Sunnanbo2011-02-19 13:13:27 +00:00Commented Feb 19, 2011 at 13:13
-
image is uploaded into a picturebox using an OpenFileDialogRiya– Riya2011-02-19 13:14:46 +00:00Commented Feb 19, 2011 at 13:14
-
Why do you need your image as a byte array? For storage? or are you trying to manipulate the image?yhw42– yhw422011-02-19 13:43:12 +00:00Commented Feb 19, 2011 at 13:43
6 Answers
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.
7 Comments
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);
1 Comment
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;
Comments
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.