3

I am creating an application that for some reasons shall only accept PNG images.

How can I check if an image is really a PNG image? Currently I am using the JavaFX 2 Image class to load the image.

Thanks for any hint!

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
stefan.at.kotlin
  • 15,347
  • 38
  • 147
  • 270

2 Answers2

2

If you don't trust the filename, a simple check is to read the first 8 bytes (with FileInputStream), and check that they correspond to the PNG signature (related: https://stackoverflow.com/a/10555053/277304)

Community
  • 1
  • 1
leonbloy
  • 73,180
  • 20
  • 142
  • 190
2

I do this currently in my own application by confirming the file's Mime Type before I process it. There are several SO threads suggesting how to obtain Mime Types in Java.

Community
  • 1
  • 1
JoshDM
  • 4,939
  • 7
  • 43
  • 72
  • 2
    I ended up Chris Mowforth's answer in http://stackoverflow.com/questions/51438/getting-a-files-mime-type-in-java: Java 7's Files.probeContentType(path) - works great in my case. So thanks for the hint :-) – stefan.at.kotlin Feb 16 '13 at 14:25