A similar library for TinyPNG for Java - compress image size

I am 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 am facing is the size of the image.

If I upload a 200 kb image, after cropping and creating its PNG it has 600 kb. This is not a solution for me, because the images are stored in the database, since the BLOB and the site load more slowly.

I am trying to find a way to compress png, have a smaller size without reducing the quality.

I could not find any library or solution to this problem. I need something for Java like TinyPNG.

Here 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!

+4

All Articles