Java中读写TIFF图像

15
我尝试了以下代码来完成读写Tiff图像的任务:
 // Define the source and destination file names.
 String inputFile = /images/FarmHouse.tif
 String outputFile = /images/FarmHouse.bmp

 // Load the input image.
 RenderedOp src = JAI.create("fileload", inputFile);

 // Encode the file as a BMP image.
 FileOutputStream stream =
     new FileOutputStream(outputFile);
 JAI.create("encode", src, stream, BMP, null);

 // Store the image in the BMP format.
 JAI.create("filestore", src, outputFile, BMP, null);

然而,当我运行代码时,我会得到以下错误信息:

Caused by: java.lang.IllegalArgumentException: Only images with either 1 or 3 bands 
can be written out as BMP files.
 at com.sun.media.jai.codecimpl.BMPImageEncoder.encode(BMPImageEncoder.java:123)
 at com.sun.media.jai.opimage.EncodeRIF.create(EncodeRIF.java:79)

有什么方法可以解决这个问题吗?

2个回答

25

最简单的读取TIFF并输出BMP的方法是使用ImageIO类:

BufferedImage image = ImageIO.read(inputFile);
ImageIO.write(image, "bmp", new File(outputFile));
你需要做的额外一件事就是确保将JAI ImageIO JAR文件添加到类路径中,因为BMP和TIFF没有安装此库的插件,JRE无法处理它们。
如果由于某种原因无法使用JAI ImageIO,则可以通过一些额外的工作使其与现有代码配合使用。正在创建的颜色模型可能是索引颜色模型,而BMP不支持它。你可以使用JAI.create("format",...)操作替换它,通过提供带有JAI.KEY_REPLACE_INDEX_COLOR_MODEL键的渲染提示来实现。
可能会有一些运气,将从文件读取的图像写入临时图像,然后写出该临时图像。
BufferedImage image = ImageIO.read(inputFile);
BufferedImage convertedImage = new BufferedImage(image.getWidth(), 
    image.getHeight(), BufferedImage.TYPE_INT_RGB);
convertedImage.createGraphics().drawRenderedImage(image, null);
ImageIO.write(convertedImage, "bmp", new File(outputFile));

我想知道你是否遇到了与常规JAI相同的索引颜色模型问题。理想情况下,除非是最简单的情况,否则应该使用ImageIO类来获取ImageReader和ImageWriter实例,以便您可以相应地调整读取和写入参数,但是可以通过调整ImageIO.read()和.write()来获得所需结果。


"ImageIO.write(image, "bmp", new File(outputFile))" 这段代码无法成功将图像以".bmp"文件格式写入。当我将代码改为使用".tiff"格式时,它就可以正常工作了。 - user224270
抱歉...有一个小错误。现在ImageIO.write应该写出转换后的图像,而不是原始图像。 - Jeff
3
“确保将JAI ImageIO JAR文件添加到类路径中”这个建议今天绝对拯救了我的理智!谢谢。” - Stewart
1
JAI的替代方案是TwelveMonkeys ImageIO,如此问题所建议(安装指南)。然后您可以像平常一样使用ImageIO.read。不需要像JAI那样使用本地库。 - Will Hardwick-Smith
2
自Java 9起,ImageIO.read支持TIFF格式,无需额外的库。 - Hemaolle

-2
FileInputStream in = new FileInputStream(imgFullPath);
FileChannel channel = in.getChannel();
ByteBuffer buffer = ByteBuffer.allocate((int)channel.size());
channel.read(buffer);
tiffEncodedImg = Base64.encode(buffer.array()); 

将这个内容(即“tiffEncodedImg”的值)作为HTML中img标签的src值使用


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接