I'm working on a website that allows users to upload images and crop them. I convert every image to .PNG for better quality. The problem I'm having is the picture size.
If I upload a 200 kb image, after cropping and making it PNG it has 600 kb. This is not a solution for me, because the images are stored in the database as BLOBs and the website loads slower.
I'm trying to find a way to compress the png, to have a smaller size, without reducing the quality.
I couldn't find any library or solution for this problem. I need something for Java like TinyPNG.
This is how I do it:
BufferedImage resizedImage = resizeImage(image,extension,width,height);
System.out.println("dimensiuni:" + resizedImage.getHeight()+ "x" + resizedImage.getWidth());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write( resizedImage, "png", baos );
baos.flush();
byte[] imageInByte = baos.toByteArray();
baos.close();
And this is the resizeImage function:
public BufferedImage resizeImage(BufferedImage image, String extension, int targetWidth, int targetHeight) {
int type = (image.getTransparency() == Transparency.OPAQUE) ?
BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
BufferedImage ret = (BufferedImage)image;
int w, h;
w = image.getWidth();
h = image.getHeight();
do {
if (w > targetWidth) {
w /= 2;
if (w < targetWidth) {
w = targetWidth;
}
}
if ( h > targetHeight) {
h /= 2;
if (h < targetHeight) {
h = targetHeight;
}
}
BufferedImage tmp = new BufferedImage(w, h, type);
Graphics2D g2 = tmp.createGraphics();
g2.setComposite(AlphaComposite.Src);
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_DEFAULT);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
g2.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
g2.drawImage(ret, 0, 0, w, h, null);
g2.dispose();
ret = tmp;
tmp.flush();
} while (w != targetWidth || h != targetHeight);
return ret;
}
Help me!!