2008-12-12 62 views
12

我正在使用Grails开发Web相册,并且正在使用grails-image-tools插件进行图像处理。如果上传的图片尺寸太大(例如:超过600 * 840),我需要一项功能来调整图片大小。在这种情况下,我需要将此图像调整为600 * 840)。什么是最有效的方法来做到这一点?非常感谢。Grails中的图像大小调整

回答

7
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) 
} 
+0

这个旋转图像虽然.... – hvgotcodes 2011-05-05 19:55:06

+0

@hvgotcodes老问题,但是发生这种情况的原因是因为图像并没有真正旋转 - 它只是具有指示照片浏览器(如浏览器)显示旋转图像的EXIF数据。有些相机(尤其是手机)会这样做,而不是实际旋转图像。由于图像没有真正旋转,并且Java API不查看EXIF旋转数据,因此图像看起来似乎旋转了,尽管实际上并非如此。这是[例子](https://gist.github.com/9re/1990019)代码,检查EXIF数据并相应地旋转。 – 2013-06-25 13:54:18

1

使用ImageTool插件。 http://grails.org/ImageTools+plugin

+0

任何想法,如果它与Grails 2兼容?是否需要从git构建自己,还是最新发布的0.1版本也在工作? – 2012-10-17 18:12:20

12

BuildConfig.groovy添加一个依赖于imgscalr

dependencies { 
    compile 'org.imgscalr:imgscalr-lib:4.1'  
} 

然后调整图像大小变成一个班轮:

BufferedImage thumbnail = Scalr.resize(image, 150);