调整上传的图片大小以便更好地查看。

3

我有一张个人头像,存储在数据库的byte[]字段中。

我想在运行时创建图像缩略图。因为我需要在网页的不同位置以不同大小显示图像。就像Facebook在评论区和其他区域中显示图像一样。

是否有任何可用的Grails插件,我可以使用Google ImageTool、ImageMagick Grails插件等。任何人都可以推荐插件或其他方法来实现这个功能。

谢谢。

1个回答

1

是的,有一个可以使用的grails插件。

请查看ImageTools插件

安装插件后,您可以使用以下语句生成所需大小的缩略图

或者,如果它是一个轻量级应用程序,并且您不想要外部依赖项...您可以使用以下代码源代码

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 ) 

  }

ImageMagick怎么样,你推荐使用这个插件吗? - Umair Saleem
@UmairSaleem:从未使用过imageMagick,所以没有评论。 - Mukul Goel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接