conversion of image to byte array
Can anyone pl开发者_C百科ease tell me how an image(.jpg,.gif,.bmp) is converted into a byte array ?
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[]));
}
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.
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);
to get the bytes from any file try:
byte[] bytes = File.ReadAllBytes(pathToFile);
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;
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.
精彩评论