我使用com.sun.media.imageioimpl.plugins.tiff.TIFFPackBitsCompressor来尝试对使用PackBits的tiff字节数组进行编码。我不熟悉这门课,也没有找到很多关于如何使用它的例子。但是,在遵循javadoc时,每次尝试编码数据时,我都会得到一个NPE。据我所见,我的任何一个值都是空的。目前,我已经用多个值尝试了这些测试,但下面是我最近的迭代:
TIFFPackBitsCompressor pack = new TIFFPackBitsCompressor();
//bImageFromConvert is a 16-bit BufferedImage with all desired data.
short[] bufferHolder = ((DataBufferUShort) bImageFromConvert.getRaster().getDataBuffer()).getData();
//Since bImageFromConvert is 16-bits, the short array isn't the right length.
//The below conversion handles tihs issue
byte[] byteBuffer = convertShortToByte(bufferHolder);
//I'm not entirely sure what this int[] in the parameters should be.
//For now, it is a test int[] array containing all 1s
int[] testint = new int[byteBuffer.length];
Arrays.fill(testint, 1);
//0 offset. dimWidth = 1760, dimHeight = 2140. Not sure what that last param is supposed to be in layman's terms.
//npe thrown at this line.
int testOut = pack.encode(byteBuffer, 0, dimWidth, dimHeight, testint, 1);有没有人对发生的事有任何洞察力?而且,如果可用的话,有没有人知道在java程序中使用PackBits编码我的TIFF文件的更好方法?
如果有什么可以让我的问题更清楚的话,请告诉我。
谢谢!
发布于 2017-03-30 08:24:16
正如注释中所说的,您不应该直接使用TIFFPackBitsCompressor,而是当您在ImageWriteParam中将"PackBits“指定为压缩类型时,JAI ImageIO TIFF插件( TIFFImageWriter)在内部使用。如果首先将压缩器实例转换为TIFFImageWriteParam,也可以在param中传递压缩器实例,但这对于插件所不知道的自定义压缩更有用。
还请注意,压缩器将只编写PackBits压缩像素数据,它不会创建完整的TIFF文件。
编写PackBits压缩TIFF文件的正常方法是:
BufferedImage image = ...; // Your input image
ImageWriter writer = ImageIO.getImageWritersByFormatName("TIFF").next(); // Assuming a TIFF plugin is installed
try (ImageOutputStream out = ImageIO.createImageOutputStream(...)) { // Your output file or stream
writer.setOutput(out);
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionType("PackBits");
writer.write(null, new IIOImage(image, null, null), param);
}
writer.dispose();使用JAI ImageIO和TwelveMonkeys ImageIO TIFF插件,上面的代码应该工作得很好。
PS:PackBits是一种非常简单的基于字节数据游程编码的压缩算法。由于16位数据在单个样本的高字节和低字节之间可能有很大差异,因此PackBits通常不是压缩此类数据的好选择。
正如我在评论中指出的,使用完全随机的值,我得到了以下结果:
Compression | File size
-----------------|-----------------
None | 7 533 680 bytes
PackBits | 7 593 551 bytes
LZW w/predictor | 10 318 091 bytes
ZLib w/predictor | 10 318 444 bytes这并不令人惊讶,因为完全随机的数据通常是不可压缩的(没有数据丢失)。对于线性梯度,它可能更类似于“摄影”图像数据,我得到了完全不同的结果:
Compression | File size
-----------------|-----------------
None | 7 533 680 bytes
PackBits | 7 588 779 bytes
LZW w/predictor | 200 716 bytes
ZLib w/predictor | 144 136 bytes正如您所看到的,这里的LZW和Deflate/Zlib算法(带有预测步骤)的性能要好得多。对于“真实”数据,可能会有更多的噪音,因此您的结果可能介于这两个极端之间。
https://stackoverflow.com/questions/43008746
复制相似问题