Search code examples
javajavax.imageio

Java ImageIO Class Drawing Image and Saving as TIFF


Java 1.8_201 on Windows 7 (32 bit) Below is my code. I can't attach the image since TIFF is not a supported format. I don't understand why the TIFF image I create has reversed the colors. The JPEG images seem OK. According to Windows Photo Viewer, the images have the following properties:

back.tif

width = 1337 pixels

height = 712 pixels

horizontal resolution = 200 dpi

vertical resolution = 200 dpi

bit depth = 1

compression = CCITT T.6

Similar for file front.tif

both.tif

width = 1340 pixels

height = 1425 pixels

horizontal resolution = 1 dpi

vertical resolution 1 dpi

bit depth = 1

compression = uncompressed

back2.jpg

width = 1337 pixels

height = 712 pixels

horizontal resolution = 200 dpi

vertical resolution = 200 dpi

bit depth = 8

(no compression details displayed)

both2.jpg

width = 1340 pixels

height = 1425 pixels

horizontal resolution = 96 dpi

vertical resolution = 96 dpi

bit depth = 8

(no compression details displayed)

My code:

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;

public class TwoImage {
    public static void main(String[] args) {
//        File back = new File("C:\\temp\\back2.jpg");
        File front = new File("C:\\temp\\front.tif"); // width = 1340 , height = 713
//        File front = new File("C:\\temp\\front2.jpg");
        File back = new File("C:\\temp\\back.tif"); // width = 1337 , height = 712
        try {
            BufferedImage bImg = ImageIO.read(back);
            BufferedImage fImg = ImageIO.read(front);
            BufferedImage img2 = new BufferedImage(1340,
                                                   1425,
//                                                   BufferedImage.TYPE_BYTE_GRAY);
                                                   BufferedImage.TYPE_BYTE_BINARY);
            Graphics2D g2D = img2.createGraphics();
            g2D.drawImage(fImg, 0, 0, null);
            g2D.drawImage(bImg, 0, 713, null);
            g2D.dispose();
//            File output = new File("C:\\temp\\both2.jpg");
            File output = new File("C:\\temp\\both.tif");
//            ImageIO.write(img2, "JPEG", output);
            ImageIO.write(img2, "TIFF", output);
        }
        catch (Exception x) {
            x.printStackTrace();
        }
    }
}

Solution

  • I wrote a test program that loads one of the TIFF images and displays it as an Icon on a JLabel and that was displayed with reversed colors. Hence I assumed that the default TIFF image reader that comes with JDK 1.8.0_201 is not appropriate here. So I guessed that I probably need to change the default settings, probably via class 'javax.imageio.plugins.tiff.TIFFImageReadParam'. But then I discovered TwelveMonkeys and its default TIFF image reader handled my TIFF images correctly and that's how I solved my problem.