Having an image file already stored into a database as a byte array, is it possible to find the image file extension from the byte array contents?
I can get the byte array from the database. I need to show the image file into the screen.
Before displaying it, I want to have the image file extension, such as .png
,.jpg
or .jpeg
, etc..
To convert a byte array to an image. Create a ByteArrayInputStream object by passing the byte array (that is to be converted) to its constructor. Read the image using the read() method of the ImageIO class (by passing the ByteArrayInputStream objects to it as a parameter).
You can try to generate an image from the byte array and check for the ArgumentException if its not. Show activity on this post. Most other types of image files have similar magick numbers. But checking that won't actually tell you if the file is a valid image file.
A byte is 8 bits (binary data). A byte array is an array of bytes (tautology FTW!). You could use a byte array to store a collection of binary data, for example, the contents of a file. The downside to this is that the entire file contents must be loaded into memory.
Most file formats have a "Magic Number" at the beginning in the form of a couple of bytes that indicates what file it is.
GIF starts with "GIF89a" or "GIF87a", i.e. bytes 47,49,46,38,39,61 or 47,49,46,38,37,61 (both hexadecimal)
JPEG starts with FF,D8 and ends with FF,D9
PNG begins with 89,50,4E,47,0D,0A,1A,0A
See more about Magic Numbers on Wikipedia
For other formats you can google the magic number. Some don't have any though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With