0

I have following method for coping jpg photos from one folder to another:

public static void copyImage(String from, String to) {
    try {
        File sourceimage = new File(from);
        BufferedImage image = ImageIO.read(sourceimage);
        ImageIO.write(image, "jpg", new File(to));
    } catch (IOException ex) {
        Logger.getLogger(ImgLib.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NullPointerException ex){
        Logger.getLogger(ImgLib.class.getName()).log(Level.SEVERE, null, ex);
    }       
}

It works, but little bit loosing quality of photo.

How I can achieve "perfect" cloning without loosing quality?

Andreas Fester
  • 36,091
  • 7
  • 95
  • 123
mondayguy
  • 973
  • 2
  • 12
  • 34

3 Answers3

1
        InputStream is = null;
        OutputStream os = null;
        try {
            is = new FileInputStream(new File("path/to/img/src"));
            os = new FileOutputStream(new File("path/to/img/dest"));
            byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
        } finally {
            is.close();
            os.close();
        }
Tanvi B
  • 1,577
  • 11
  • 14
1

Yes, you are right. In this line:

ImageIO.write(image, "jpg", new File(to));

Your method is still re-encoding the image data which, with a lossy format like JPEG, will inevitably cause a loss of fidelity in the image.

I think, you may try to copy the image file using this code:

    InputStream is = null;
    OutputStream os = null;
    try {
        is = new FileInputStream(new File("path/to/img/src"));
        os = new FileOutputStream(new File("path/to/img/dest"));
        byte[] buffer = new byte[8192];
        int length;
        while ((length = is.read(buffer)) > 0) {
            os.write(buffer, 0, length);
        }
    } finally {
        is.close();
        os.close();
    }

Also, you may Apache Commons IOUtils to simplify copying from one stream to the other or if you are using Java 8 then you can just call Files.copy method.

halfer
  • 19,824
  • 17
  • 99
  • 186
Teocci
  • 7,189
  • 1
  • 50
  • 48
0

You have used BufferedImage which read the file into a image object. instead you should read and write image file in the same way as you do with binary files (use InputStraem and OutputStream).

Mohit Thakur
  • 565
  • 5
  • 12