[英]Java clone jpg without losing quality of image
我有以下方法将jpg照片从一个文件夹复制到另一个文件夹:
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);
}
}
它可以工作,但是照片质量稍有下降。
如何在不损失质量的情况下实现“完美”克隆?
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();
}
是的,你是对的。 在这一行:
ImageIO.write(image, "jpg", new File(to));
您的方法仍在对图像数据进行重新编码,这种图像数据采用JPEG之类的有损格式,将不可避免地导致图像保真度下降。
我认为,您可以尝试使用以下代码复制图像文件:
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();
}
另外,您可以使用Apache Commons IOUtils简化从一个流到另一个流的复制,或者如果您使用的是Java 8,则可以只调用Files.copy方法。
您已经使用BufferedImage将文件读入图像对象。 相反,您应该以与处理二进制文件相同的方式读写图像文件(使用InputStraem和OutputStream)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.