Scale a BufferedImage the fastest and easiest way

前端 未结 6 593
春和景丽
春和景丽 2020-12-28 15:03

The task: I have some images, I scale them down, and join them to one image. But I have a little problem with the implementation:

The concr

6条回答
  •  滥情空心
    2020-12-28 15:37

    I get it with this method, it resizes the Image and tries to maintain the proportions:

    /**
    * Resizes an image using a Graphics2D object backed by a BufferedImage.
    * @param srcImg - source image to scale
    * @param w - desired width
    * @param h - desired height
    * @return - the new resized image
    */
    private BufferedImage getScaledImage(BufferedImage src, int w, int h){
        int finalw = w;
        int finalh = h;
        double factor = 1.0d;
        if(src.getWidth() > src.getHeight()){
            factor = ((double)src.getHeight()/(double)src.getWidth());
            finalh = (int)(finalw * factor);                
        }else{
            factor = ((double)src.getWidth()/(double)src.getHeight());
            finalw = (int)(finalh * factor);
        }   
    
        BufferedImage resizedImg = new BufferedImage(finalw, finalh, BufferedImage.TRANSLUCENT);
        Graphics2D g2 = resizedImg.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2.drawImage(src, 0, 0, finalw, finalh, null);
        g2.dispose();
        return resizedImg;
    }
    

提交回复
热议问题