繁体   English   中英

如何在Java中制作图像的精确副本?

[英]How to make an exact copy of image in java?

加载图像后,我想创建图像的精确副本,从而使质量和比例保持不变。 使用我当前的代码,质量降低了。

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

尝试只复制您的图像文件,使用此代码:

        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方法,请在文档中进行检查

从使用:

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

请执行以下操作:(这里没有我的开发环境来对此进行测试,但请以为我对您有帮助。)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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