Does ImageIO.read() take EXIF orientation metadata into account? - java

In JPEG images, EXIF metadata is sometimes included and tells in what orientation the image should be shown.
The question is, whether Java's ImageIO.read() takes EXIF into account while reading a JPEG image, and automatically applies the transformation.
More concretely, if I use Java's ImageIO for converting a JPEG image with EXIF into a PNG image, is the orientation of the PNG image going to be correct? Or is the below code going to produce a PNG image without taking EXIF orientation instructions into account?
private byte[] convertToPng(byte[] imageFileAsByteArray) {
ByteArrayInputStream bis = new ByteArrayInputStream(imageFileAsByteArray);
BufferedImage bi = ImageIO.read(bis);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(bi, "png", bos);
return bos.toByteArray();
}

The short answer is, unfortunately, no; ImageIO.read(..) (by default) does not take the Exif Orientation tag into account. Your PNG will be not be rotated accordingly.
However, all ImageIO.read(..) does internally, is to look up an appropriate ImageReader plug-in for the input, and delegate reading to it. And while the JRE-bundled plug-in does not take Exif into account, it is possible to add support for it, in a third-party ImageReader. Unfortunately, I don't know of any that do, but I am considering adding Exif orientation support to the TwelveMonkeys ImageIO JPEGImageReader in the future.
In the mean time, you have to apply the rotation yourself, by reading the metadata and rotating. The value of the orientation tag can be acquired either using the ImageIO JPEG metadata or some third-party library. I think both the mentioned metadata-extractor or TwelveMonkeys ImageIO can be used for this purpose. JAI ImageIO (using the TIFF metadata) can probably also do this.
If using the ImageIO JPEG metadata, be aware:
Note that an application wishing to interpret Exif metadata given a metadata tree structure in the javax_imageio_jpeg_image_1.0 format must check for an unknown marker segment with a tag indicating an APP1 marker and containing data identifying it as an Exif marker segment.

I have struggled with jpeg exif orientation for awhile, and now that I set out to fix my problems, I find that they are gone. To make sure for myself, I simplified OP.s example so as to read
public static void main (String [] args) throws Exception {
java.io.File in = new java.io.File ("in.jpg");
java.io.File out = new java.io.File ("out.png");
BufferedImage image = ImageIO.read (new FileInputStream(in));
ImageIO.write (image, "png", out);
}
in.jpg is a picture with exif orientation tag 8, tilted to the left. When I run the example, out.png is created as a properly oriented png picture. So it seems that ImageIo has learned something recently.

Related

The Thumbnailator library converts image to cmyk

I'm reading an image at full size with correct orientation with the Thumbnailator library which honors EXIF orientation flags.
InputStream is = new BufferedInputStream( new FileInputStream(filepath) );
BufferedImage image = Thumbnails.of(is).scale(1).asBufferedImage();
ImageIO.write(image, "jpg", new File(filepath));
But after converting the colorls are vrong so I checked the color model with XnView and it shows jpeg cmyk.
The original image was rgb. So why colors are wrong after using Thumbnailator library?
I was facing the same problem. I resolved the issue by saving it as PNG. Thumbnailator has got several issues and like the version (0.x.x) suggests there is no stable version out yet.
You can find the detailed solution at this link

imageIO to open .HDR file

I need to open an .hdr file and work on it, but imageIO doesn't supports that format.
The problem is that I need to keep the information loss as little as possible: 32bpc is perfect, 16 is fine and less the 16 won't work.
There are 3 possible solutions I came up to:
Find a plugin that allow me to open .HDR file. I've been searching for it a lot but without luck;
Find a way to convert the .HDR file to a format I can find a plugin for. Tiff maybe? Tried this too but still no luck;
Reduce the dynamic range from 32bpc to 16bpc and then convert it to png. This is tricky because once I have a png file I win, but it's not that easy to cut the range without killing the image..
What would you recommend me to do? Do you know a way to make one of those 3 options works? Or do you have a better idea?
You can now read .HDR using ImageIO. :-)
This is a first version, so it might be a little rough around the edges, but should work for standard (default settings) Radiance RGBE .HDR files.
The returned image will be a custom BufferedImage with a DataBufferFloat backing (ie., samples will be in 3 samples, 32-bit float interleaved RGB format).
By default, a simple global tone-mapping is applied, and all RGB values will be normalized to range [0...1] (this allows anyone to just use ImageIO.read(hdrFile) and the image will look somewhat reasonable, in a very reasonable time).
It is also possible to pass an HDRImageReadParam to the ImageReader instance with a NullToneMapper. This is even faster, but the float values will be unnormalized, and might exceed the max value. This allows you to do custom, more sophisticated tone-mapping on the image data, before converting to something more displayable.
Something like:
// Create input stream
ImageInputStream input = ImageIO.createImageInputStream(hdrFile);
try {
// Get the reader
Iterator<ImageReader> readers = ImageIO.getImageReaders(input);
if (!readers.hasNext()) {
throw new IllegalArgumentException("No reader for: " + hdrFile);
}
ImageReader reader = readers.next();
try {
reader.setInput(input);
// Disable default tone mapping
HDRImageReadParam param = (HDRImageReadParam) reader.getDefaultReadParam();
param.setToneMapper(new NullToneMapper());
// Read the image, using settings from param
BufferedImage image = reader.read(0, param);
}
finally {
// Dispose reader in finally block to avoid memory leaks
reader.dispose();
}
}
finally {
// Close stream in finally block to avoid resource leaks
input.close();
}
// Get float data
float[] rgb = ((DataBufferFloat) image.getRaster().getDataBuffer()).getData();
// TODO: Custom tone mapping on float RGB data
// Convert the image to something easily displayable
BufferedImage converted = new ColorConvertOp(null).filter(image, new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB));
// Optionally write as JPEG or other format
ImageIO.write(converted, "JPEG", new File(...));

Decoding of old style JPEG-in-TIFF data is not supported

I need to display the 3rd page of scanned tiff files. i used the code
TIFFReader reader = new TIFFReader(new File(pathOfFile));
RenderedImage image = reader.getPage(2);
its sometimes work. and show error : Decoding of old style JPEG-in-TIFF data is not supported.
I used aspriseTIFF.jar
then how i solve this problem.
please reply.
thanks in advance
The problem you have run into is that "old style" JPEG compression in the TIFF format (compression == 6), is not supported in the library you use.
This is quite common I guess, as "old-style" JPEG compression is deprecated in TIFF, because it was never fully specified. And because of this under-specification, various vendors implemented it in different, incompatible ways. Support was dropped in favor for TIFF compression 7, JPEG.
Unfortunately, old TIFF files using this compression still exists, so you need to find another library. The good news is that you can use ImageIO and a proper plug-in.
Using a TIFF ImageReader plug-in, like the one from my TwelveMonkeys ImageIO open source project, you should be able to do this:
// Create input stream
try (ImageInputStream input = ImageIO.createImageInputStream(file)) {
// Get the reader
ImageReader reader = ImageIO.getImageReaders(input).next();
try {
reader.setInput(input);
// Read page 2 of the TIFF file
BufferedImage image = reader.read(2, null);
}
finally {
reader.dispose();
}
}
(sorry about the try/finally boiler-plate, but it is important to avoid resource/memory leaks).

How to read Bytes of an Image in Java?

I am currently working with Image processing in Java. Initially I used ImageIO class to write images
ImageIO.write(image,"jpg",os);
the problem with this method is am lossing the actual image size and quality. Then I preferred ByteStream
Files.readAllBytes(fi.toPath());
to read and
fos.write(fileContent);
to write Images. This works perfectly. The issue I am facing here is I can read only files but not Images(ie, BuffreredImage image). Is it possible to read a Image rather than files here or should I move to someother IO?
Code Snippet is here,
try {
File fnew=new File("d:\\3\\IMG1.jpg");
java.io.FileOutputStream fos = new java.io.FileOutputStream(new File("d:\\3\\Test1\\4.jpg"));
File fi = new File("d:\\3\\7.jpg");
byte[] fileContent = Files.readAllBytes(fi.toPath());
fos.write(fileContent);
} catch (Exception e) {
System.out.println("Exception");
}
Any Kind of suggestions or help will be appreciated. Thanks in Advance.
the problem with this method is am lossing the actual image size and quality. Then I preferred ByteStream
When you read a JPEG with with ImageIO, it is converting the JPEG to a Bitmap automatically. Then when you write it, it is encoding to a JPEG again (which loses quality).
Just replace ImageIO.write(image,"jpg",os) with ImageIO.write(image,"png",os) and you are done. A lossless format such as PNG will not lose any data when you write the image.
BufferedImage getRGB() will get you all the actual pixel data for the image. There will be no compression or anything like JPEG. It will be the raw image.
Edited to add an example based on my comments...
BufferedImage image = ImageIO.read(new File("google.jpg"));
ImageWriter w = ImageIO.getImageWritersBySuffix("jpg").next();
ImageOutputStream out = ImageIO.createImageOutputStream(new File("output.jpg"));
w.setOutput(out);
ImageWriteParam param = new JPEGImageWriteParam(Locale.getDefault());
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(1);
w.write(null, new IIOImage(image, null, null), param);
out.close();

Convert a bitmap image to an uncompressed tif image in Java

I'm trying to convert a bitmap image into an uncompressed tif file for use with the Tesseract OCR engine.
I can use this method to produce a compressed tif file...
final BufferedImage bmp = ImageIO.read(new File("input.bmp"));
ImageIO.write(bmp, "jpg", new File("output.tif"));
This produces an empty tif file when the "jpg" is changed to tif as these files are dealt with in Java Advanced Imaging (JAI).
How can I create an uncompressed tif image? Should I decompress the tif image produced from the above code or is there another way to handle the conversion process?
Any examples provided would be much appreciated.
Thanks
kingh32
You can use ImageWriteParam to disable compression:
TIFFImageWriterSpi spi = new TIFFImageWriterSpi();
ImageWriter writer = spi.createWriterInstance();
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_DISABLED);
ImageOutputStream ios = ImageIO.createImageOutputStream(new File("output.tif"));
writer.setOutput(ios);
writer.write(null, new IIOImage(bmp, null, null), param);
Some time before i was facing the problems with tiff images reading and conversion with jai.
I found that it need to install support for working with tiff images in jai, then it works fine for me u can also get it form here:
https://cds.sun.com/is-bin/INTERSHOP.enfinity/WFS/CDS-CDS_Developer-Site/en_US/-/USD/ViewProductDetail-Start?ProductRef=jaiio-1.0_01-oth-JPR#CDS-CDS_Developer
and install over a jvm then it will also work for you.
you can also have a look here
Java / JAI - save an image gray-scaled

Categories