如何在Java中制作图像的精确副本? [英] How to make an exact copy of image in java?

查看:75
本文介绍了如何在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();
        }

如果您使用的是 Java 8 ,则只需调用Files.copy方法,然后在

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

这篇关于如何在Java中制作图像的精确副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆