views:

133

answers:

9

What is the need/purpose of converting an image to a byte array?

Why do we need to do this?

A: 

If it is a image file use File.ReadAllBytes().

crauscher
+4  A: 

I think the most common use would be saving an image in a database (BINARY(MAX) data type).

Brad
A: 
public byte[] imageToByteArray(System.Drawing.Image image)
{
 MemoryStream ms = new MemoryStream();
 image.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
 return ms.ToArray();
}
Georgi
Thanks, but it's not what i'm asking... i'm asking, why we have to do this conversion?
Mike
+2  A: 

Most common is to persist the image in the database as a blob (binary large object) but it could also be used in web services where you could take in a byte array as a method argument and then convert that to an image for whatever reason.

Chris Conway
A: 

To further generalize what Brad said: Serialization and (probably) a basis for object comparison.

trevman
+5  A: 

What's the purpose of converting an Image to a byte array?

  • Saving an image to disk

  • Serializing the image to send to a web service

  • Saving the image to a database

  • Serializing the image for processing

...are just a few that I can think of off the top of my head.

Justin Niessner
A: 

Also is helpful if you have a image in memory and want to send it to someone via a protocol (HTTP for example). A perfect example would be the method "AddBytesForUpload" in the Chilkat HTTPRequest clas [http://www.chilkatsoft.com/refdoc/vbnetHttpRequestRef.html].

Why would you ever need to do this you may ask... Well lets assume we have a directory of images we want to auto upload to imageshack, but do some mods before hand like put our domain name at the bottom right. With this, u load the image in memory, do the mods with it that u need, then simply attach that stream to the HTTPRequest object. Without the array u would need to then same to a file before uploading, which in turn will create either a new file u then need to delete after, or over write the original, which is not always ideal.

Anthony Greco
+1  A: 

the only time i've ever needed to do this was to compare two images pixel-by-pixel to see if they were identical (as part of an automated test suite). converting to bytes and pinning the memory allowed me to use an unsafe block in C# to do a direct pointer-based comparison, which was orders of magnitude faster than GetPixel.

Steven A. Lowe
+1  A: 

Recently I wrote a code to get hash from image, here is how:

    private ImageConverter c = new ImageConverter();
    private byte[] getBitmapHash(Bitmap hc) {
        return md5.ComputeHash(c.ConvertTo(hc, typeof(byte[])) as byte[]);
    }

Here is this in context. Serializing image or adding it to database in raw byte format (without mime type) is not something that seems to be sensible, but you can do that. Image processing and cryptography are most likely of places where this is useful.

Margus