Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to find an image file extension from its byte array contents? [duplicate]

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..

like image 949
user3782196 Avatar asked Oct 17 '14 13:10

user3782196


People also ask

How can I get image from byte array?

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).

How do you check if a byte array is a valid image Java?

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.

What is stored in a byte array?

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.


1 Answers

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.

like image 71
Ghostkeeper Avatar answered Sep 20 '22 08:09

Ghostkeeper