【发布时间】:2010-09-26 14:47:24
【问题描述】:
我正在使用 Grails 开发网络相册,对于图像处理,我正在使用 grails-image-tools 插件。如果上传的图像尺寸太大(例如:超过 600 * 840 ),我需要一个调整图像大小的功能。在这种情况下,我需要将此图像的大小调整为 600 * 840)。最有效的方法是什么?非常感谢。
【问题讨论】:
标签: java grails image-processing frameworks
我正在使用 Grails 开发网络相册,对于图像处理,我正在使用 grails-image-tools 插件。如果上传的图像尺寸太大(例如:超过 600 * 840 ),我需要一个调整图像大小的功能。在这种情况下,我需要将此图像的大小调整为 600 * 840)。最有效的方法是什么?非常感谢。
【问题讨论】:
标签: java grails image-processing frameworks
import java.awt.Image as AWTImage
import java.awt.image.BufferedImage
import javax.swing.ImageIcon
import javax.imageio.ImageIO as IIO
import java.awt.Graphics2D
static resize = { bytes, out, maxW, maxH ->
AWTImage ai = new ImageIcon(bytes).image
int width = ai.getWidth( null )
int height = ai.getHeight( null )
def limits = 300..2000
assert limits.contains( width ) && limits.contains( height ) : 'Picture is either too small or too big!'
float aspectRatio = width / height float requiredAspectRatio = maxW / maxH
int dstW = 0
int dstH = 0
if (requiredAspectRatio < aspectRatio) {
dstW = maxW dstH = Math.round( maxW / aspectRatio)
} else {
dstH = maxH dstW = Math.round(maxH * aspectRatio)
}
BufferedImage bi = new BufferedImage(dstW, dstH, BufferedImage.TYPE_INT_RGB)
Graphics2D g2d = bi.createGraphics() g2d.drawImage(ai, 0, 0, dstW, dstH, null, null)
IIO.write( bi, 'JPEG', out )
}
【讨论】:
使用 ImageTool 插件。 https://grails.org/plugin/image-tools 附言仅适用于 grails v2。
【讨论】:
在BuildConfig.groovy 中添加对imgscalr 的依赖
dependencies {
compile 'org.imgscalr:imgscalr-lib:4.1'
}
然后调整图像大小就变成了单行:
BufferedImage thumbnail = Scalr.resize(image, 150);
【讨论】:
import org.imgscalr.Scalr