I need to scale down an JPG image so that it fits in a 1024x640 rectangle and save it so that it's size is no more than 20 kB. With some googling, I managed to do both. For the scaling I use
private static BufferedImage scale(BufferedImage input, int width, int height) {
final int type = input.getTransparency() == Transparency.OPAQUE ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
final BufferedImage result = new BufferedImage(width, height, type);
final Graphics2D g2 = result.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(input, 0, 0, width, height, null);
g2.dispose();
return result;
}
and for the size-reduction, I use ImageWriter
with JPEGImageWriteParam
and repeat with decreased quality until the file size gets below the limit.
It both works rather nicely on my machine, but on the test server, it does terrible things:
original file size: 174548
scaled down file size: 16995 - on my machine
228218 - on the server
So the scaled-down image is bigger than the original and the quality is awful.
I though it could be related to the headless java problem, but the java installation is not headless (and I never get an HeadlessException
):
java -version
openjdk version "1.8.0_222"
OpenJDK Runtime Environment (build 1.8.0_222-8u222-b10-1ubuntu1~16.04.1-b10)
OpenJDK 64-Bit Server VM (build 25.222-b10, mixed mode)
Any idea what's going on?
The problem was the resizing done using Graphics2D
. Not idea why it did what it did, but after replacing it with java-image-scaling, the problem is gone.
It's quite possible that there are better libraries out there, but for current needs this one works good enough.