[英]JAI Tiff to JPEG convertion issue
I have an issue converting Tiff-Files to JPEGs with JAI.我在使用 JAI 将 Tiff 文件转换为 JPEG 时遇到问题。 This is my Code:
这是我的代码:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
TIFFDecodeParam param = null;
ImageDecoder dec = ImageCodec.createImageDecoder("tiff", new FileSeekableStream(inPath), param);
RenderedImage op = dec.decodeAsRenderedImage(0);
JPEGEncodeParam jpgparam = new JPEGEncodeParam();
jpgparam.setQuality(67);
ImageEncoder en = ImageCodec.createImageEncoder("jpeg", baos, jpgparam);
en.encode(op);
Mostly this code works fine, but with some Images, I got the following error:大多数情况下,这段代码可以正常工作,但是对于一些图像,我得到了以下错误:
java.lang.RuntimeException: Only 1, or 3-band byte data may be written.
at com.sun.media.jai.codecimpl.JPEGImageEncoder.encode(JPEGImageEncoder.java:142)
I cant find any related Problems over here and i have no idea how to fix it.我在这里找不到任何相关的问题,我不知道如何解决它。 The Images who throw this error have a high Resolution (9000 x 7000 or more) and are mostly scans of old pictures.
抛出此错误的图像具有高分辨率(9000 x 7000 或更高),并且主要是旧图片的扫描。
Image with this ColorModel works:使用此 ColorModel 的图像有效:
ColorModel:
#pixelBits = 24
numComponents = 3
color space = java.awt.color.ICC_ColorSpace@21981a50
transparency = 1 has alpha = false
isAlphaPre = false
This not:这不是:
ColorModel:
#pixelBits = 16
numComponents = 1
color space = java.awt.color.ICC_ColorSpace@88a30ad
transparency = 1 has alpha = false
isAlphaPre = false
I tried reading the JPEG standard, and it is not readily clear whether this is a limitation of the JPEG format or just the Encoder.我尝试阅读 JPEG 标准,但尚不清楚这是 JPEG 格式的限制还是仅仅是编码器的限制。
The encoder provide with java only encodes 1 or 3 byte bands, so in your case there are 16bit gray scale images. java 提供的编码器仅编码 1 或 3个字节带,因此在您的情况下有 16 位灰度图像。 One way to solve this, as it appears you have done, is to save the image using a PNG encoder.
正如您所做的那样,解决此问题的一种方法是使用 PNG 编码器保存图像。 It would not support the compression quality parameter.
它不支持压缩质量参数。
The other way to handle this would be to save your image as an 8bit gray scale image.处理此问题的另一种方法是将图像保存为 8 位灰度图像。
I made a simple example to test this w/out JAI.我做了一个简单的例子来测试这个没有 JAI。
public static void main(String[] args) throws Exception{
BufferedImage img = new BufferedImage(256, 256, BufferedImage.TYPE_USHORT_GRAY);
Iterator<ImageWriter> writers = ImageIO.getImageWritersBySuffix("jpg");
while( writers.hasNext() ){
ImageWriter writer = writers.next();
ImageOutputStream ios = ImageIO.createImageOutputStream( new File("junk.jpg") );
writer.setOutput(ios);
writer.write(img);
}
}
The simplest way I can see to convert it is to create a new image and draw to it with a graphics.我能看到的最简单的转换方法是创建一个新图像并用图形绘制它。
BufferedImage img2 = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
Graphics g = img2.getGraphics();
g.drawImage(img, 0, 0);
g.dispose();
Then img2
can be saved as JPG.然后
img2
可以保存为JPG。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.