如何使用OpenCV Java压缩图像并存储到特定文件夹

时间:2016-05-24 09:02:34

标签: java opencv image-processing javacv

您好我想压缩并将压缩图像存储到文件夹。所以我使用了以下代码,

import java.io.*;
import java.util.*;
import java.awt.image.*;

import javax.imageio.*;
import javax.imageio.stream.ImageOutputStream;

public class Compression {

    public static void main(String[] args) throws IOException {

        String dc = "C:\\Users\\admin\\Desktop\\RFI\\DC\\1_1_c.jpg";
        String dr = "C:\\Users\\admin\\Desktop\\RFI\\DR";

        File file = new File(dc);
        BufferedImage image = ImageIO.read(file);
        OutputStream os =new FileOutputStream(new File(dr));
        Iterator<ImageWriter>writers =  ImageIO.getImageWritersByFormatName("jpg");
        ImageWriter writer = (ImageWriter) writers.next();

        ImageOutputStream ios = ImageIO.createImageOutputStream(os);
        writer.setOutput(ios);

        ImageWriteParam param = writer.getDefaultWriteParam();

        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(0.05f);
        writer.write(null, new IIOImage(image, null, null), param);

        os.close();
        ios.close();
        writer.dispose();
    }
}

但我没有得到压缩图片。仅在控制台上获得以下错误

Exception in thread "main" javax.imageio.IIOException: Can't read input file!
    at javax.imageio.ImageIO.read(ImageIO.java:1301)
    at com.opencv.Compression.main(Compression.java:18)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

请建议我任何想法......

1 个答案:

答案 0 :(得分:1)

这应该得到的评论不仅仅是一个答案,但由于我的声誉如此之低,我无法评论,我不得不把它作为答案。

您是否尝试了解错误?调用堆栈非常清楚。您在第BufferedImage image = ImageIO.read(file);行有错误。该程序找不到您的图像。您确定String dc = "C:\\Users\\admin\\Desktop\\RFI\\DC\\1_1_c.jpg";中指定的图像文件确实存在吗?