Java JAI - Converting TIFF to PNG Results With Black Line on the Right Side of Image

Viewed 321

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

1 Answers
Related