Reputation: 3
I have a method that compress image to jpg format and returns an byte array of it. Here is a code of it:
public static byte[] CompressToJpeg(BufferedImage image, float compressionQuality) throws IOException {
File compressedImageFile = new File("compressed_image.jpg");
OutputStream os = new FileOutputStream(compressedImageFile);
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
ImageWriter writer = (ImageWriter) writers.next();
ImageOutputStream ios = ImageIO.createImageOutputStream(os);
writer.setOutput(ios);
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(compressionQuality);
writer.write(null, new IIOImage(image, null, null), param);
os.close();
ios.close();
writer.dispose();
return Files.readAllBytes(compressedImageFile.toPath());
}
And always when i run this compression for the first time it takes much longer than in next runs. My question is why is this happening ?
Upvotes: 0
Views: 192
Reputation: 27084
As mentioned in the link I posted in the comments, this is common for all things Java:
The first time execution of anything Java is always going to be slower than subsequent runs. There is a startup-overhead, because...
Generally:
The ImageIO
class especially has to do a lot of things on start-up:
(Plus, probably more things I didn't think of).
Upvotes: 1