Reputation: 1063
I have a profile picture which i stored in database in a byte[] field.
What I want do is to create image thumbnails at runtime. Because I have to show images in different sizes on different place on a web page. Something like facebook, which show image in a comment section and other areas.
Any grails plugin which i can use, i have google imageTool, imageMagick grails plugin. Anyone can recommend the plugin for any other approach to do that.
Thanks.
Upvotes: 3
Views: 710
Reputation: 8467
Yes there is a grails
plugin that you can use.
See this ImageTools plugin
After installing the plugin you may use following statement to generate thumbnail of desired size
Or if its a thin app and you dont want external dependencies.. you may use the following code Source
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 )
}
Upvotes: 1