Reputation: 41
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);
}
}
Upvotes: 0
Views: 14947
Reputation: 50
Go from using:
ImageIO.write(cImg, "jpg", saveImage);
To the following: (Don't have my dev environment here to test this but think I have this close for you.)
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();
Upvotes: 0
Reputation: 3190
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();
}
if you are using Java 8 then you can just call Files.copy
method, check it in the docs
Upvotes: 6