我有一个 jpg 图像,我想将其转换为 tiff 文件,但是当我从 byteArrayOutputStream 创建输出文件时,输出文件的字节长度为 0。
public static void main(String[] args) throws Exception {
String root = "E:\\Temp\\imaging\\test\\";
File image = new File(root + "0riginalTif-convertedToJpg.JPG");
byte[] bytes = compressJpgToTiff(image);
File destination = new File(root + "OriginalJpg-compressedToTiff.tiff");
FileOutputStream fileOutputStream = new FileOutputStream(destination);
fileOutputStream.write(bytes);
}
public static byte[] compressJpgToTiff(File imageFile) throws Exception {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(255);
ImageOutputStream imageOutputStream = null;
try {
File input = new File(imageFile.getAbsolutePath());
Iterator<ImageWriter> imageWriterIterator = ImageIO.getImageWritersByFormatName("TIF");
ImageWriter writer = imageWriterIterator.next();
imageOutputStream = ImageIO.createImageOutputStream(byteArrayOutputStream);
writer.setOutput(imageOutputStream);
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionType("JPEG");
param.setCompressionQuality(0.1f);
BufferedImage bufferedImage = ImageIO.read(input);
writer.write(null, new IIOImage(bufferedImage, null, null), param);
writer.dispose();
return byteArrayOutputStream.toByteArray();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (imageOutputStream != null)
imageOutputStream.close();
byteArrayOutputStream.close();
}
}
我想尽可能减小输出 tiff 的大小。有更好的方法吗?是否有可能减小 tiff 图像的大小?
return byteArrayOutputStream.toByteArray();
,但您没有将数据写入byteArrayOutputStream
。看,您刚刚将数据添加到 writer
。
关于tiff文件的压缩,你已经用-
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
完成了
您的 byteArrayOutputStream 对象在使用 byteArrayOutputStream.toByteArray()
将 byteArrayOutputStream 转换为 byteArray 之前在
finally块中关闭,这就是为什么您的内容长度为 0。因此,请修改您的代码一次,如下所示:
public static byte[] compressJpgToTiff(File imageFile) throws Exception {
//Add rest of your method code here
writer.dispose();
byte[] bytesToReturn = byteArrayOutputStream.toByteArray();
return bytesToReturn;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (imageOutputStream != null)
imageOutputStream.close();
byteArrayOutputStream.close();
}
}
在获取 byteArray 之前,您需要执行
imageOutputStream.flush()
:
BufferedImage bufferedImage = ImageIO.read(input);
writer.write(null, new IIOImage(bufferedImage, null, null), param);
writer.dispose();
imageOutputStream.flush();
return byteArrayOutputStream.toByteArray();