2

I want to retrieve images from a database (MySQL, saved as a LongBlob field). They can be .gif, .jpg or .png images. Returning them to the client from the servlet requires using something like, to set the content type:

response.setContentType("image/gif");

But this only works properly in all browsers if the image is a gif. Can I identify if the image is a gif or jpg by reading the bytes or can I specify a generic ContentType that handles all images.

Ankur
  • 47,089
  • 107
  • 237
  • 309

4 Answers4

4

The URLConnection#guessContentTypeFromStream() can recognize those three formats.

InputStream input = resultSet.getBinaryStream("columnname");
response.setContentType(URLConnection.guessContentTypeFromStream(input));
OutputStream output = response.getOutputStream();
// Write input to output.

If it might happen that it returns null or a !contentType.startsWith("image"), then you'd like to supply a generic image content-type of just "image". Most if not all webbrowsers are forgiving in this.

BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
  • Thanks BalusC ... unfortunately using Safari it doesn't seem to work, rather than displaying the file, it gives the option of downloading it - which is what I am trying to avoid. Funnily enough using image/gif seems to work for gif/jpg/png files ... but I haven't tried IE yet. – Ankur Dec 18 '10 at 14:47
  • @Ankur - can you check the response content type? Add a breakpoint and see what's being set. – Bozho Dec 18 '10 at 21:44
  • @Ankur: what does `URLConnection#guessContentTypeFromStream()` say for each of those images? Based on its source code it should be able to recognize gif, jpeg and png based on the file headers. – BalusC Dec 18 '10 at 22:23
  • URLConnection#guessContentTypeFromStream() = null ... :( – Ankur Dec 20 '10 at 04:27
2

There are a few byte sequences you can detect. JPEG images all start with FF D8 for example. Just look at a few images with a hex editor and check for similarities at the beginning.

DanMan
  • 10,431
  • 3
  • 36
  • 57
2

All image formats do put in their signature at the start of the file. When saving the file in the database you can go ahead and figure the value out, and then save it as another database column, so as to cache it for later reuse.

GIF file start with GIF as the first three characters. Similarly, PNG files has the same three characters, JPEG files start with the value 0xF8 0xD8. The following URL lists various signatures of image file formats. http://www.garykessler.net/library/file_sigs.html

sangupta
  • 2,336
  • 3
  • 22
  • 36
1

You can use a 3rd party library like jMimeMagic.

Also this link has a good comparison of various ways of getting the Mime type of a file (it includes libraries like: Apache Tika, JMimeMagic etc. with some code samples.)

SANN3
  • 7,856
  • 4
  • 54
  • 84