2010-05-24 56 views
13

写出TIFF图像我尝试下面的代码来完成读写TIFF图像的任务:阅读和Java中

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

任何想法我能如何解决这个问题?

回答

20

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

BufferedImage image = ImageIO.read(inputFile); 
ImageIO.write(image, "bmp", new File(outputFile)); 

的唯一额外的事情,你需要做的就是这个工作是确保你”已将JAI ImageIO JAR添加到类路径中,因为没有来自此库的插件,JRE不处理BMP和TIFF。

如果因为某些原因无法使用JAI ImageIO,可以使用它来使用现有的代码,但是您必须做一些额外的工作。正在为您正在加载的TIFF创建的颜色模型可能是一种不受BMP支持的索引颜色模型。您可以使用JAI.KEY_REPLACE_INDEX_COLOR_MODEL键提供渲染提示,将其替换为JAI.create(“format”,...)操作。

你可能有一些运气写从文件中读取的图像转换成一个临时的图像,然后写出临时图像:

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()进行调整以提供给您你想要什么。

+0

“ImageIO.write(图像, ”BMP“,新文件(OUTPUTFILE))” 是不僵硬书写能够成功地将图像写为“.bmp”文件。当我将代码更改为“.tiff”时,它会起作用。 – user224270 2010-05-24 19:20:17

+0

对不起...有一个小的错字。 ImageIO.write现在应该写出convertedImage,而不是原始图像。 – Jeff 2010-05-24 19:24:04

+0

谢谢杰夫。有效!你真的救了我的一天;) – user224270 2010-05-24 19:36:49

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

使用此内容在HTML img标签的SRC值( “tiffEncodedImg” 的,即价值)