-1

I have problem returning jpg format. When my file is in jpg format, the final format is jpeg. My method:

public String getImageFormat(InputStream input) throws IOException {
    ImageInputStream stream = ImageIO.createImageInputStream(input);
    Iterator<ImageReader> iter = ImageIO.getImageReaders(stream);
    if (!iter.hasNext())
        return null;
    ImageReader reader = iter.next();
    ImageReadParam param = reader.getDefaultReadParam();
    reader.setInput(stream, true, true);
    try {
        reader.read(0, param);
        return reader.getFormatName();
    } finally {
        reader.dispose();
        stream.close();
    }
}

I noticed that Image reader for jpg in orginatingProvider returns something like this: enter image description here

I would like to receive the actual format of the photo, has anyone had such a case and knows how to solve it?

Radek
  • 61
  • 1
  • 5
  • Are you saying there is a difference between "JPG" and "JPEG" ? – matt Jan 10 '22 at 13:39
  • I just mean if I am able to return the real photo format, if input has a photo; image.jpg 'then I would like to return as jpg, if; jpeg' then jpeg. At the moment my method for 'jpg, jpeg' photos returns jpeg format and I can't tell them apart. – Radek Jan 10 '22 at 13:44
  • 2
    You cannot tell them apart because they're [the same thing](https://kinsta.com/blog/jpg-vs-jpeg/). jpg is just a short version since some file systems only had 3 letter extensions. – matt Jan 10 '22 at 13:50
  • `jpeg` is the correct name as it is the mime type `image/jpeg` https://www.w3.org/Graphics/JPEG/ - `jpg` ist just the (old) file extension for file-systems where only 8.3 file-names were allowed. – Robert Jan 10 '22 at 15:30

1 Answers1

0

As the comments already points out, there is nothing wrong about the format name. The actual format is really called "JPEG", short for "Joint Photographic Experts Group". The reason .jpg or .JPG is typically used for file extension, is due to the fact that arcane file systems only allowed 3 letter file extensions.

If, on the other hand, what you really want to know is the file extension, use a File object, and extract the part of the file name after the dot. Using ImageIO is way overkill for such a task.

File file = new File(...); 

String fileName = file.getName();
int index = fileName.lastIndexOf('.');

if (index >= 0) {
    return fileName.substring(index + 1);
}

// No period found
return null;
Harald K
  • 26,314
  • 7
  • 65
  • 111