Creating image thumbnails through Grails ImageTools plugin
In one of the projects recently, we had to generate the thumbnails dynamically from the client-provided images. We decided to use the Grails plugin named: ImageTools. This is a very basic plugin but provided very quick and stable solution to our use-case. You can read more about the plugin and how to install it here .
We decided to implement the solution in the form of a tag which gave us the ease to use it directly in a .gsp file. Here is how the code looked like in a taglib:
import org.grails.plugins.imagetools.ImageTool // Import the ImageTool class in your taglib. def thumbnail = { attrs ->; def imgSrc = attrs['imgSrc'] // as the name suggests - the image source def dimension = attrs['dimension'].toInteger() //size of the image - giving 200 as a dimension gives you the thumbnail of around 200*200 in size. def imageTool = new ImageTool() imageTool.load(imgSrc) imageTool.square() imageTool.thumbnail(dimension) imageTool.writeResult(thumbnailLocation,"JPEG") //thumbnailLocation - provides the path to where you want to store the thumbnail image. out << thumbnailLocation }
This is all you need to create the thumbnail programatically through ImageTools plugin. The code above always creates the new thumbnail; we tried to improvise the above solution by saving the thumbnail in a folder and checking for the existence of the thumbnail before actually creating the thumbnail. This is how we achieved it:
def thumbnail = {attrs ->; def imgSrc = attrs['imgSrc'] def dimension = attrs['dimension'].toInteger() def thumbLocation = "/path/to/store/thumbnails" + imgSrc def file // if thumbnail already exists, return the path to the image if((file = new File(thumbLocation)).exists()){ out << thumbLocation } else{ // the code to generate the thumbnail comes here. } }
Hope this helps.
— Abhishek
Intelligrape Software