What is the need/purpose of converting an image to a byte array?
Why do we need to do this?
What is the need/purpose of converting an image to a byte array?
Why do we need to do this?
I think the most common use would be saving an image in a database (BINARY(MAX)
data type).
public byte[] imageToByteArray(System.Drawing.Image image)
{
MemoryStream ms = new MemoryStream();
image.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
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.
To further generalize what Brad said: Serialization and (probably) a basis for object comparison.
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.
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.
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.
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.