Tag Archives: imageTools

Adding and Resizing Images with Grails

Here is a quick post on how to upload images within your Grails project to your file system(rather than your database). It seems simple enough, but I ran into a few snags as I was working on one of my projects. Just wanted to provided a working example for those that are entering the Grails territory for the first time. Happy Coding!

I am using the imageTools plugin which you can read more about here

NOTE: The imageTools plugin has been criticized for its low quality of output. ImageMagick may be a better fit for you project(s). My particular project didn’t call for high quality pictures. A quick google search for “imagemagick for grails” should get you started on your way.

I am using version 1.0.3 in the example below

to install, I ran the following command from my grails application’s root directory

grails install-plugin http://www.arquetipos.co.cr/blog/files/grails-image-tools-1.0.3.zip

Domain-Class

class Picture {
byte[] imagefile
//Any other stuff you want to track

}

Controller Code for Saving an image

def save = {

def downloadedfile = request.getFile('imagefile')
def pictureInstance = new Picture(params)
def imageTool = new ImageTool()

if(downloadedfile && pictureInstance.save()){
String imagepath = grailsAttributes.getApplicationContext().getResource("images/").getFile().toString() + File.separatorChar + "${pictureInstance.id}.jpg"
downloadedfile.transferTo(new File(imagepath))

imageTool.load(imagepath)
imageTool.thumbnail(140)

imageTool.writeResult(imagepath, "JPEG")
imageTool.square()
flash.message = "Picture ${pictureInstance.id} created"
redirect(action:show,id:pictureInstance.id)
}
else {
render(view:'create',model:[pictureInstance:pictureInstance])
}
}

Code for displaying the image in both the ‘show’ and ‘list’ views

<td><img src="${createLinkTo(dir:'images', file: pictureInstance.id+'.jpg' )}" /> </td>