Search code examples
javaopencvimage-processingjavacv

How to compress image and store to specific folder using OpenCV Java


Hi I want to compress and store compressed image to folder. So I have used the below code,

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();
    }
}

But i'm not get compressed image. Only get the below error on console

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)

Please suggest me any idea....


Solution

  • This would deserve a comment more than an answer but since my reputation is so low, I can't comment and am forced to write it as an answer.

    Did you try to understand the error you get ? The call stack is pretty clear. You have an error at the line BufferedImage image = ImageIO.read(file);. The program can't find your image. Did you make sure that the image file specified in String dc = "C:\\Users\\admin\\Desktop\\RFI\\DC\\1_1_c.jpg"; actually existed ?