Scale a BufferedImage the fastest and easiest way

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

    The Graphics object has a method to draw an Image while also performing a resize operation:

    Graphics.drawImage(Image, int, int, int, int, ImageObserver) method can be used to specify the location along with the size of the image when drawing.

    So, we could use a piece of code like this:

    BufferedImage otherImage = // .. created somehow
    BufferedImage newImage = new BufferedImage(SMALL_SIZE, SMALL_SIZE, BufferedImage.TYPE_INT_RGB);
    
    Graphics g = newImage.createGraphics();
    g.drawImage(otherImage, 0, 0, SMALL_SIZE, SMALL_SIZE, null);
    g.dispose();
    

    This will take otherImage and draw it on the newImage with the width and height of SMALL_SIZE.


    Or, if you don't mind using a library, Thumbnailator could accomplish the same with this:

    BufferedImage newImage = Thumbnails.of(otherImage)
                                 .size(SMALL_SIZE, SMALL_SIZE)
                                 .asBufferedImage();
    

    Thumbnailator will also perform the resize operation quicker than using Image.getScaledInstance while also performing higher quality resize operations than using only Graphics.drawImage.

    Disclaimer: I am the maintainer of the Thumbnailator library.

提交回复
热议问题