0

我目前正在尝试使用以下代码将 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);

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

4

1 回答 1

0

我怀疑调用ImageIO.read(srcInStream);返回 null(表明您没有为 TIFF 注册的 ImageReader)。你怎么知道你成功读取了图像?

于 2013-10-16T17:21:07.360 回答