图像在Grails中调整大小 [英] Image resize in Grails

查看:102
本文介绍了图像在Grails中调整大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am developing a Web Album using Grails and for image processing, I am using grails-image-tools plugin. I need a functionality to resize the images if the uploaded images size is too big (for eg: more than 600 * 840 ) . In this case I need to resize this image to 600 * 840). What is the most efficient way to do this? Thanks a lot.

推荐答案

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

这篇关于图像在Grails中调整大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆