我有一个java.awt.Image,我需要添加CCITT T.6压缩并转换为TIFF字节数组。我已经看到了一些使用TIFFImageWriteParam和javax.imageio包中的其他类的例子,但我找不到从Image到byte数组的完整示例。
这是我到目前为止从扫描获得的java.awt.Image开始的。这可以很好地生成TIFF的字节数组,但我需要找到一种方法,使用TIFFImageWriteParam或其他方法,在将TIFF作为字节数组处理之前压缩它:
thisImage = ... a java.awt.Image from a scanner
if(thisImage!=null){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedImage bimg = new BufferedImage(thisImage.getWidth(null),thisImage.getHeight(null), BufferedImage.TYPE_BYTE_BINARY);
bimg.createGraphics().drawImage(thisImage, 0, 0, null);
try {
ImageIO.write(bimg, "tiff", baos);
} catch (Exception e) {
e.printStackTrace();
}
thisByteArray = baos.toByteArray();
...
任何帮助将不胜感激。
答案 0 :(得分:2)
我找到了一个解决方案,感谢:this thread.
以下是我最终解决的问题:
thisImage = thisImage = ... a java.awt.Image from a scanner
if(thisImage!=null){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
boolean foundWriter = false;
BufferedImage bimg = new BufferedImage(thisImage.getWidth(null),thisImage.getHeight(null), BufferedImage.TYPE_BYTE_BINARY);
bimg.createGraphics().drawImage(thisImage, 0, 0, null);
for(Iterator<ImageWriter> writerIter = ImageIO.getImageWritersByFormatName("tif"); writerIter.hasNext() && !foundWriter;) {
foundWriter = true;
ImageWriter writer = (ImageWriter)writerIter.next();
writer.setOutput(ios);
TIFFImageWriteParam writeParam = (TIFFImageWriteParam)writer.getDefaultWriteParam();
writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
writeParam.setCompressionType("CCITT T.6");
writer.prepareWriteSequence(null);
ImageTypeSpecifier spec = ImageTypeSpecifier.createFromRenderedImage(bimg);
javax.imageio.metadata.IIOMetadata metadata = writer.getDefaultImageMetadata(spec, writeParam);
IIOImage iioImage = new IIOImage(bimg, null, metadata);
writer.writeToSequence(iioImage, writeParam);
bimg.flush();
writer.endWriteSequence();
ios.flush();
writer.dispose();
ios.close();
thisByteArray = baos.toByteArray();
baos.close();
}
}