图像在Grails中调整大小

Omn*_*ent 13 java grails frameworks image-processing

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

Dón*_*nal 14

imgscalr中BuildConfig.groovy添加依赖

dependencies {
    compile 'org.imgscalr:imgscalr-lib:4.1'     
}
Run Code Online (Sandbox Code Playgroud)

然后调整图像大小成为一个单行:

BufferedImage thumbnail = Scalr.resize(image, 150);
Run Code Online (Sandbox Code Playgroud)

  • 是的,您需要导入Scalr类.将以下内容添加到您执行调整大小`import org.imgscalr.Scalr的类的导入列表中 (3认同)

War*_*ior 8

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 )
} 
Run Code Online (Sandbox Code Playgroud)