Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# How to convert pictureBox.Image to Byte Array? [duplicate]

Tags:

c#

picturebox

I looking for fast way Picturebox in image Convert to byte array.

I saw this code but i don't need it. because Picture box of images is the data read from the db. So I don't know ImageFormat

public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
    MemoryStream ms = new MemoryStream();
    imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
    return ms.ToArray();
}

So Please let me know if anybody know fast way

Thanks! have a good time!

like image 432
Mr.MK Avatar asked Feb 10 '15 08:02

Mr.MK


2 Answers

Try to read this: http://www.vcskicks.com/image-to-byte.php Hope it will help you out.

Edit: I guess that you have your code snip from link that Fung linked. If so, there is the answer for you question right there you just need to scroll down...

2nd Edit (code snippet from page - thanks for info Fedor):

public static byte[] ImageToByte(Image img)
{
    ImageConverter converter = new ImageConverter();
    return (byte[])converter.ConvertTo(img, typeof(byte[]));
}
like image 160
eren Avatar answered Nov 19 '22 18:11

eren


This might not be exactly what you're looking for, but it might be useful to you if you're looking for performance in doing some pixel operations .. and I thought it would be worth mentioning it here.

Since you've already loaded the image with Image imageIn you can actually directly access the image buffer without doing any copies hence saving time and resources :

public void DoStuffWithImage(System.Drawing.Image imageIn)
{
    // Lock the bitmap's bits.  
    Rectangle rect = new Rectangle(0, 0, imageIn.Width, imageIn.Height);
    System.Drawing.Imaging.BitmapData bmpData =
                    imageIn.LockBits(rect, System.Drawing.Imaging.ImageLockMode.Read,
                    imageIn.PixelFormat);

    // Access your data from here this scan0,
    // and do any pixel operation with this imagePtr.
    IntPtr imagePtr = bmpData.Scan0;

    // When you're done with it, unlock the bits.
    imageIn.UnlockBits(bmpData);
}

For some more information, look at this MSDN page

ps: This bmpData.Scan0 will of course give you only access to the pixel payload. aka, no headers !

like image 2
DarkUrse Avatar answered Nov 19 '22 16:11

DarkUrse