Scale a BufferedImage the fastest and easiest way

前端 未结 6 517
春和景丽
春和景丽 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:28

    Maybe this method will help:

    public  BufferedImage resizeImage(BufferedImage image, int width, int height) {
             int type=0;
            type = image.getType() == 0? BufferedImage.TYPE_INT_ARGB : image.getType();
            BufferedImage resizedImage = new BufferedImage(width, height,type);
            Graphics2D g = resizedImage.createGraphics();
            g.drawImage(image, 0, 0, width, height, null);
            g.dispose();
            return resizedImage;
         }
    

    Don't forget those "import" lines:

    import java.awt.Graphics2D;
    import java.awt.image.BufferedImage;
    

    And about casting:

    The abstract class Imageis the superclass of all classes that represent graphical images. We can't cast Image to BufferedImage because every BufferedImage is Image but vice versa is not true.

    Image im = new BufferedImage(width, height, imageType);//this is true
    
    BufferedImage img = new Image(){//.....}; //this is wrong
    

提交回复
热议问题