简体   繁体   中英

How to make an exact copy of image in java?

After loading the image, I want to create an exact copy of the image whereby the quality and scale can remain the same. With my current code, the quality was reduced.

public class Image {
    private static final String path = "C:/Users.../src/7horses.jpg";
    private static final File file = new File(path);

    static BufferedImage deepCopy(BufferedImage bi) throws IOException {
        String saveAs = "copy.jpg";
        ColorModel cm = bi.getColorModel();
        boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
        WritableRaster raster = bi.copyData(null);
        BufferedImage cImg = new BufferedImage(cm, raster, isAlphaPremultiplied, null);
        File saveImage = new File("C:/Users.../src", saveAs);
        ImageIO.write(cImg, "jpg", saveImage);
        return cImg;
    }

    public static void main(String[] args) throws IOException {
        BufferedImage cp, img;
        img = ImageIO.read(file); 
        cp = deepCopy(img);
    }
}

try just to copy your image file, use 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[1024];
            int length;
            while ((length = is.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
        } finally {
            is.close();
            os.close();
        }

if you are using Java 8 then you can just call Files.copy method, check it in the docs

Go from using:

ImageIO.write(cImg, "jpg", saveImage);

To the following: (Don't have my dev environment here to test this but think I have this close for you.)

Iterator iterator = ImageIO.getImageWritersByFormatName("jpeg");
ImageWriter writer = (ImageWriter)iterator.next();
ImageWriteParam imageWriteParam = writer.getDefaultWriteParam();


imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
imageWriteParam.setCompressionQuality(1); //0 is max Compression  1 is max quality

FileImageOutputStream output = new FileImageOutputStream(saveImage);
writer.setOutput(output);

IIOImage image = new IIOImage(cImg, null, null);
writer.write(null, image, iwp);
writer.dispose();
output.close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM