Create Multi-Page Tiff with Java

后端 未结 1 586
不知归路
不知归路 2021-01-01 05:37

I\'m interested in taking a tif image and adding a layer to it that contains text with Java, preferably with the Twelve Monkeys image library if possible.

I can twe

相关标签:
1条回答
  • 2021-01-01 06:27

    You can write multi-page images (in formats that supports it, like TIFF), using the standard ImageIO API. Now that Java ImageIO comes with a TIFF plugin bundled, starting from Java 9, the below should just work, with no extra dependencies. For Java 8 and earlier, you still need a TIFF plugin, like JAI or TwelveMonkeys as mentioned.

    See for example the TIFFImageWriterTest.testWriteSequence method from the TwelveMonkeys ImageIO project's test cases, for an example of how to do it.

    The important part:

    BufferedImage[] images = ...
    OutputStream stream = ... // May also use File here, as output
    
    // Obtain a TIFF writer
    ImageWriter writer = ImageIO.getImageWritersByFormatName("TIFF").next();
    
    try (ImageOutputStream output = ImageIO.createImageOutputStream(stream)) {
        writer.setOutput(output);
    
        ImageWriteParam params = writer.getDefaultWriteParam();
        params.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    
        // Compression: None, PackBits, ZLib, Deflate, LZW, JPEG and CCITT variants allowed
        // (different plugins may use a different set of compression type names)
        params.setCompressionType("Deflate");
    
        writer.prepareWriteSequence(null);
    
        for (BufferedImage image : images) {
            writer.writeToSequence(new IIOImage(image, null, null), params);
        }
    
        // We're done
        writer.endWriteSequence();
    }
    
    writer.dispose();
    
    0 讨论(0)
提交回复
热议问题