我有一个应用程序,用户可以在相册中上传图片,但上传的图像自然需要调整大小,以便还有拇指可用,并且显示的图片也适合页面(例如800x600)。
我调整大小的方式是这样的:
Image scaledImage = img.getScaledInstance((int)width, (int)height, Image.SCALE_SMOOTH);
BufferedImage imageBuff = new BufferedImage((int)width, (int)height, BufferedImage.TYPE_INT_RGB);
Graphics g = imageBuff.createGraphics();
g.drawImage(scaledImage, 0, 0, new Color(0,0,0), null);
g.dispose();
而且效果还不错。我唯一的问题是g.drawImage()
方法似乎非常慢,我无法想象用户有足够的耐心等待上传 20 张图片 20*10 秒 ~ 3 分钟。事实上,在我的电脑上,为一张图片调整 3 种不同的大小需要花费近 40 秒的时间。
这还不够好,我正在寻找更快的解决方案。我想知道是否有人可以告诉我 Java 中更好的一个,或者通过调用 shell 脚本、命令,无论你知道什么黑客,它必须更快,这次其他一切都不重要。
我使用类似于以下的代码来缩放图像,我删除了处理保留纵横比的部分。每张图像的性能绝对优于 10 秒,但我不记得任何确切的数字。为了在缩小尺寸时获得更好的质量,如果原始图像大于所需缩略图大小的两倍,则应分几个步骤进行缩放,每个步骤都应将前一个图像缩放至其大小的大约一半。
public static BufferedImage getScaledImage(BufferedImage image, int width, int height) throws IOException {
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();
double scaleX = (double)width/imageWidth;
double scaleY = (double)height/imageHeight;
AffineTransform scaleTransform = AffineTransform.getScaleInstance(scaleX, scaleY);
AffineTransformOp bilinearScaleOp = new AffineTransformOp(scaleTransform, AffineTransformOp.TYPE_BILINEAR);
return bilinearScaleOp.filter(
image,
new BufferedImage(width, height, image.getType()));
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)