以最快最简单的方式扩展BufferedImage [英] Scale a BufferedImage the fastest and easiest way

查看:689
本文介绍了以最快最简单的方式扩展BufferedImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任务:
我有一些图像,我将它们缩小,然后将它们连接到一个图像。但是我对实现有一点问题:

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:

具体问题:
我想调整大小/缩放BufferedImage。 getScaledInstance方法返回一个Image对象,但我无法将其强制转换为BufferedImage:

The concrete problem: I want to resize/scale a BufferedImage. The getScaledInstance method returns an Image object, but I can't cast it to BufferedImage:

Exception in thread "main" java.lang.ClassCastException: sun.awt.image.ToolkitImage cannot be cast to java.awt.image.BufferedImage

(我不知道为什么它是ToolkitImage而不是Image ......)

(I don't know why is it a ToolkitImage instead of an Image...)

我找到了解决方案:

Image tmp = bi.getScaledInstance(SMALL_SIZE, SMALL_SIZE, BufferedImage.SCALE_FAST);
BufferedImage buffered = new BufferedImage(SMALL_SIZE,SMALL_SIZE,BufferedImage.TYPE_INT_RGB);
buffered.getGraphics().drawImage(tmp, 0, 0, null);

但它很慢,我认为应该有更好的方法。

我需要BufferedImage,因为我必须让像素加入小图像。

I need the BufferedImage, because I have to get the pixels to join the small images.

有更好的(更好/更快)的方式吗?

编辑:
如果我首先将Image转换为ToolkitImage,它有一个getBufferedImage()方法。但它总是返回null。你知道为什么吗?

If I cast the Image first to ToolkitImage, it has a getBufferedImage() method. But it always returns null. Do you know why?

推荐答案

Graphics 对象有一个方法在执行调整大小操作的同时绘制图像

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

Graphics.drawImage(Image,int,int,int,int,ImageObserver) 方法可用于指定绘图时的位置以及图像的大小。

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();

这将花费 otherImage 并绘制它 newImage ,宽度和高度为 SMALL_SIZE

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

或者,如果您不介意使用库,请 Thumbnailator 可以完成同样的事情:

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也会比使用 Image.getScaledInstance更快地执行调整大小操作同时还执行更高质量的调整大小操作,而不是仅使用 Graphics.drawImage

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

免责声明:我是Thumbnailator库的维护者。

这篇关于以最快最简单的方式扩展BufferedImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆