Skip to content

Instantly share code, notes, and snippets.

@manute
Created May 14, 2013 11:26
Show Gist options
  • Save manute/5575258 to your computer and use it in GitHub Desktop.
Save manute/5575258 to your computer and use it in GitHub Desktop.
Cropping image - grails controller
package com.images
import java.awt.image.BufferedImage
import javax.imageio.ImageIO
import grails.converters.JSON
class CroopingController {
def s3ImageService
def confirmImage(){
def photoS3Object = s3ImageService.photo(params.original_photo)
def imageCrooped = cropping(photoS3Object)
render ("ok_cropped" as JSON)
}
private cropping(photoFromS3){
def posx = parseIntTheValueDoubleAsString(params.dimension_x)
def posy = parseIntTheValueDoubleAsString(params.dimension_y)
def width = parseIntTheValueDoubleAsString(params.dimension_w)
def height = parseIntTheValueDoubleAsString(params.dimension_h)
BufferedImage image = ImageIO.read(photoFromS3)
withException{
def position_y = calculatePositonHeight(height,posy,image.height)
def position_x = calculatePositonWidth(width,posx,image.width)
return image.getSubimage( position_x, position_y , width , height )
}
}
private withException(closure){
try{
closure()
}catch(all){
log.error "Error when cropping image",all
render ("error_cropped" as JSON)
}
}
private parseIntTheValueDoubleAsString(value){
Double.parseDouble(value) as Integer
}
private calculatePositonHeight(height,posy,heightOriginal){
if(isHeightOutOfRaster(height,posy,heightOriginal)){
return heightOriginal - height
}
return posy
}
private calculatePositonWidth(width,posx,widthOriginal){
if(isWidthOutOfRaster(width,posx,widthOriginal)){
return widthOriginal - width
}
return posx
}
private isHeightOutOfRaster(height,posy,heightOriginal){
height + posy > heightOriginal
}
private isWidthOutOfRaster(width,posx,widthOriginal){
width + posx > widthOriginal
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment