使用javax进行Java Tiff图像压缩

时间:2013-10-16 17:13:17

标签: java javax.imageio

我目前正在尝试使用以下代码将tiff图像压缩为较小的jpg文件:

 public ImageHandler(String srcPath, String destPath, float qual) throws IOException{
    this.pathToSourceImage = srcPath;
    this.pathToDestImage = destPath;
    this.quality = qual;
    this.sourceImage = new File(pathToSourceImage);
    this.destImage = new File(pathToDestImage);
    this.srcInStream = new FileInputStream(sourceImage);
    this.destOutStream = new FileOutputStream(destImage);
}

private void compress() throws IOException{
        BufferedImage image = ImageIO.read(srcInStream);
        System.out.println("Got the bufferedImage");
        Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");

        if(!writers.hasNext()){
            throw new IllegalStateException("No Writers Found!");
        }

        ImageWriter writer = (ImageWriter) writers.next();
        ImageOutputStream imageOutStream = ImageIO.createImageOutputStream(destOutStream);
        writer.setOutput(imageOutStream);

        ImageWriteParam param = writer.getDefaultWriteParam();

        //Compress at quality
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(quality);

        writer.write(null, new IIOImage(image, null, null), param);

        srcInStream.close();
        destOutStream.close();
        imageOutStream.close();
        writer.dispose();


    }


 public static void main(String args[]){
        String tifPath = "C:\\00000000.090.tif";
        String compressedJpgPath = "C:\\compressed.jpg";
        float quality = 0.5f;

        try{
            ImageHandler testHandler = new ImageHandler(tifPath, compressedJpgPath, quality);
            testHandler.compress();
        }catch(IOException e){
            e.printStackTrace();
        }
    }

即使我可以让它成功地将源tif读入缓冲区,它仍然会引发以下错误:

Exception in thread "main" java.lang.IllegalArgumentException: image == null!
at javax.imageio.IIOImage.<init>(IIOImage.java:109)
at fjimagecompressor.ImageHandler.compress(ImageHandler.java:82)
at fjimagecompressor.ImageHandler.main(ImageHandler.java:99)

在这一行:

writer.write(null, new IIOImage(image, null, null), param);

即使不是,图像如何将自身报告为null?

1 个答案:

答案 0 :(得分:0)

我怀疑对ImageIO.read(srcInStream);的调用返回null(表示您没有为TIFF注册ImageReader)。你怎么知道你成功阅读了这张照片?