2008-12-12 61 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);