[英]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.