Convert java.awt.Image to TIFF byte array with com

2019-05-22 05:46发布

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.

1条回答
Deceive 欺骗
2楼-- · 2019-05-22 06:48

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<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();
  }
}
查看更多
登录 后发表回答