What is the best way to scale images in Java?

前端 未结 7 1100
时光取名叫无心
时光取名叫无心 2020-12-30 06:14

I have a web application written in Java (Spring, Hibernate/JPA, Struts2) where users can upload images and store them in the file system. I would like to scale those images

7条回答
  •  误落风尘
    2020-12-30 06:40

    Found this to be faster:

    public static BufferedImage getScaledInstance(final BufferedImage img, final int targetWidth, final int targetHeight,
                                                  final Object hint) {
        final int type = BufferedImage.TYPE_INT_RGB;
        int drawHeight = targetHeight;
        int drawWidth = targetWidth;
        final int imageWidth = img.getWidth();
        final int imageHeight = img.getHeight();
        if ((imageWidth <= targetWidth) && (imageHeight <= targetHeight)) {
            logger.info("Image " + imageWidth + "/" + imageHeight + " within desired scale");
            return img;
        }
        final double sar = ((double) imageWidth) / ((double) imageHeight);
        if (sar != 0) {
            final double tar = ((double) targetWidth) / ((double) targetHeight);
            if ((Math.abs(tar - sar) > .001) && (tar != 0)) {
                final boolean isSoureWider = sar > (targetWidth / targetHeight);
                if (isSoureWider) {
                    drawHeight = (int) (targetWidth / sar);
                }
                else {
                    drawWidth = (int) (targetHeight * sar);
                }
            }
        }
        logger.info("Scaling image from " + imageWidth + "/" + imageHeight + " to " + drawWidth + "/" + drawHeight);
        final BufferedImage result = new BufferedImage(drawWidth, drawHeight, type);
        try {
            final Graphics2D g2 = result.createGraphics();
            try {
                if (hint != null) {
                    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
                }
                g2.drawImage(img, 0, 0, drawWidth, drawHeight, null);
            }
            finally {
                g2.dispose();
            }
            return result;
        }
        finally {
            result.flush();
        }
    }
    

提交回复
热议问题