This is the first google result for "How to use imgscalr in grails", and I was surprised at the lack of information and examples when it ran it. Although the first answer is close, there are still a few errors that need to be fixed.
For those who ended here like me through google, here is a more detailed example of how to use this beautiful plugin correctly:
First declare the plugin in the BuildConfig.groovy file:
dependencies { // specify dependencies here under either 'build', 'compile', 'runtime', 'test' or 'provided' scopes eg. // runtime 'mysql:mysql-connector-java:5.1.20' compile 'org.imgscalr:imgscalr-lib:4.2' }
Then, after installation, just paste this piece of code into your controller, in an action that gets a multi-part form with the image uploaded.
def create() { def userInstance = new User(params) //saving image def imgFile = request.getFile('myFile') def webRootDir = servletContext.getRealPath("/") userInstance.storeImageInFileSystem(imgFile, webRootDir) (...) }
Inside my domain, I implemented this storeImageInFileSystem method, which will resize the image and save it to the file system. But first import this into a file:
import org.imgscalr.Scalr import java.awt.image.BufferedImage import javax.imageio.ImageIO
And then we implement the method:
def storeImageInFileSystem(imgFile, webRootDir){ if (!imgFile.empty) { def defaultPath = "/images/userImages" def systemDir = new File(webRootDir, defaultPath) if (!systemDir.exists()) { systemDir.mkdirs() } def imgFileDir = new File( systemDir, imgFile.originalFilename) imgFile.transferTo( imgFileDir ) def imageIn = ImageIO.read(imgFileDir); BufferedImage scaledImage = Scalr.resize(imageIn, 200); //200 is the size of the image ImageIO.write(scaledImage, "jpg", new File( systemDir, imgFile.originalFilename )); //write image in filesystem (...) } }
It worked for me. Change any details as necessary, such as a system pointer or image size.