2

Following couple of examples I found on SO an online, I am trying to convert a TIFF image I receive from an REST endpoint to PNG image using code below:

public void TiffToPng(byte[] tiffBytes, ByteArrayOutputStream output) throws IOException {
    // ALL GOOD, no black line shows
    try (OutputStream fos = new FileOutputStream("C:\\mytiff.tiff")) {
        fos.write(tiffBytes);
        fos.flush();
    }

    SeekableStream stream = new ByteArraySeekableStream(tiffBytes);
    ImageDecoder decoder = ImageCodec.createImageDecoder("tiff", stream, null);
    
    try {
        RenderedImage renderedImage = decoder.decodeAsRenderedImage(0);
        PNGEncodeParam pngEncodeParam = PNGEncodeParam.getDefaultEncodeParam(renderedImage);
        pngEncodeParam.setBitDepth(1);

        ImageEncoder encoder = ImageCodec.createImageEncoder("png", output, pngEncodeParam);
        encoder.encode(renderedImage);
        
        // PROBLEM! image has black line
        byte[] pngBytes = output.toByteArray(); 
        try (OutputStream fos = new FileOutputStream("C:\\mypng.png")) {
            fos.write(pngBytes);
            fos.flush();
        }
    } catch (Exception e) {
        System.out.println("Error: " + e.getMessage());
    } finally {
        stream.close();
    }
}

The problem is that the converted image gets a black line on the right side.

If I persist TIFF bytes above to a TIFF file, there is no black line.

If I persist PNG bytes above to A PNG file, the black line shows on the right side which tells me that the conversion process is the culprit.

enter image description here

pixel
  • 9,653
  • 16
  • 82
  • 149

1 Answers1

1

You can try with more recent library than jai: jai-imageio-core 1.4.0

Then the code use an intermediate bufferedImage:

BufferedImage tif = ImageIO.read(new File("C:\\mytiff.tiff"));
ImageIO.write(tif, "png", new File("C:\\mypng.png"));

I think you are using a binary image (black/white) and if the width of the image is not a multiple of 8, this problem may occur.

Stéphane Millien
  • 3,238
  • 22
  • 36