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

时间:2014-07-17 15:28:21

标签: java image

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

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

2 个答案:

答案 0 :(得分:2)

尝试复制图像文件,使用以下代码:

        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方法,请在docs

中查看

答案 1 :(得分:0)

从使用开始:

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