7

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

Xavi López
  • 27,550
  • 11
  • 97
  • 161
user3782196
  • 113
  • 1
  • 6
  • 1
    No, not the original file extension (because it can be anything), but you can find the picture type by examining the "magic number": http://en.wikipedia.org/wiki/Magic_number_(programming) https://www.netspi.com/blog/entryid/185/magic-bytes-identifying-common-file-formats-at-a-glance – Tom Oct 17 '14 at 13:40
  • It depends on the file type. Some of them will carry this information, some of them won't -- it depends on the format. Also, each format will have to be considered separately, because each one that does store this information will store it in different places from the others. – Software Engineer Oct 17 '14 at 14:50

2 Answers2

6

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.

Ghostkeeper
  • 2,830
  • 1
  • 15
  • 27
1

The Java Mime Magic Library could also help here (it is a Java library for determining the MIME type of files or streams).

https://github.com/arimus/jmimemagic

http://sourceforge.net/projects/jmimemagic/

Pier-Alexandre Bouchard
  • 5,135
  • 5
  • 37
  • 72