当前位置:   article > 正文

java图片字节数组压缩,使用压缩将java.awt.Image转换为TIFF字节数组

使用 tiffimagewriteparam param = (tiffimagewriteparam)writer.getdefaultwrite

I have a java.awt.Image that I need to add CCITT T.6 compression and convert to a TIFF byte array. I have seen some examples of using TIFFImageWriteParam and other classes from the javax.imageio package but I can’t find a complete example going all the way from Image to byte array.

Here is what I have so far beginning with a java.awt.Image obtained from scanning. This works just fine to generate a byte array of a TIFF, but I need to find a way, using TIFFImageWriteParam or some other means, to compress the TIFF prior to processing it as a byte array:

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

...

Any help would be appreciated.

解决方案

I found a solution thanks to: this thread.

Here is what I ended up doing that solved my issue:

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

}

}

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/694784
推荐阅读
相关标签
  

闽ICP备14008679号