How to combine two or many tiff image files in to one multipage tiff image in JAVA

陌路散爱 提交于 2019-11-29 04:23:34
Gilbert Le Blanc

I hope you have the computer memory to do this. TIFF image files are large.

You're correct in that you need to use the Java Advanced Imaging (JAI) API to do this.

First, you have to convert the TIFF images to a java.awt.image.BufferedImage. Here's some code that will probably work. I haven't tested this code.

BufferedImage image[] = new BufferedImage[numImages];
for (int i = 0; i < numImages; i++) {
    SeekableStream ss = new FileSeekableStream(input_dir + file[i]);
    ImageDecoder decoder = ImageCodec.createImageDecoder("tiff", ss, null);
    PlanarImage op = new NullOpImage(decoder.decodeAsRenderedImage(0), null, null, OpImage.OP_IO_BOUND);
    image[i] = op.getAsBufferedImage();
}

Then, you convert the BufferedImage array back into a multiple TIFF image. I haven't tested this code either.

TIFFEncodeParam params = new TIFFEncodeParam();
OutputStream out = new FileOutputStream(output_dir + image_name + ".tif"); 
ImageEncoder encoder = ImageCodec.createImageEncoder("tiff", out, params);
Vector vector = new Vector();   
for (int i = 0; i < numImages; i++) {
    vector.add(image[i]); 
}
params.setExtraImages(vector.listIterator(1)); // this may need a check to avoid IndexOutOfBoundsException when vector is empty
encoder.encode(image[0]); 
out.close(); 

Good luck.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!