java生成tiff,用Java读写TIFF图像

在尝试使用Java加载和编码TIFF图像为BMP格式时,遇到'只有1或3带图像可以作为BMP文件写入'的错误。解决方法是使用ImageIO类,或者如果必须使用原始代码,则需要处理颜色模型,例如通过创建一个新的BufferedImage并转换源图像的颜色模型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I tried the following code to accomplish the task of reading and writing tiff images:

// 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);

However, when I run the code, I get the following error message:

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)

Any idea how I could solve this issue?

解决方案

The easiest way to read in a TIFF and output a BMP would be to use the ImageIO class:

BufferedImage image = ImageIO.read(inputFile);

ImageIO.write(image, "bmp", new File(outputFile));

The only additional thing you would need to do to get this to work is make sure you've added the JAI ImageIO JARs to your classpath, since BMP and TIFF are not handled by the JRE without the plugins from this library.

If you can't use JAI ImageIO for some reason, you can get it to work with your existing code but you'll have to do some additional work. The color model that is being created for the TIFF that you are loading is probably an indexed color model which is not supported by a BMP. You can replace it with the JAI.create("format",...) operation by providing a rendering hint with a key of JAI.KEY_REPLACE_INDEX_COLOR_MODEL.

You may have some luck writing the image read from file into a temporary image and then writing out the temp image:

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));

I'm wondering if you're running into the same index color model issue as with the regular JAI. Ideally you should be using the ImageIO class to get ImageReader and ImageWriter instances for all but the simplest cases so that you can tweak the read and write params accordingly, but the ImageIO.read() and .write() can be finessed to give you what you want.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值