在Java中将jpg压缩并转换为tiff

时间:2018-11-19 11:12:58

标签: java image jpeg tiff

我有一个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图片的尺寸吗?

2 个答案:

答案 0 :(得分:0)

return byteArrayOutputStream.toByteArray();,但您没有将数据写入byteArrayOutputStream。看,您刚刚将数据添加到了writer

关于tiff文件的压缩,您已经使用-param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);

答案 1 :(得分:0)

在使用byteArrayOutputStream.toByteArray()将byteArrayOutputStream转换为byteArray之前,您的 byteArrayOutputStream 对象在 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();
}
}