Search code examples
imagemagickcropimage-manipulationminimagick

How to upscale crop dimensions


I am using minimagick. I am using resize_to_fit: [300, nil] to show an image to a user and then using jcrop to allow them to crop the image. I am saving jcrop coordinates width, height, x and y.

I want to use these coordinates to crop a larger version of the image. To get this larger version I am using resize_to_fit: [600, nil] on the original.

I would like to crop the image using size and offset, but obviously I can't use the coords that I have from jcrop.

Is there a way to upscale the coordinates so that when I use them to crop the 600px wide image it will look the same as what the user entered for the 300px wide image?


Solution

  • My workflow is just about what you describe, except that I work with images scaled exactly 25%.

    I crop the scaled image using either ImageMagick's "display" or GraphicsMagick's "display" and save as PNG (using the same filename with only the extension changed from JPG to png). This records the cropping geometry in the PNG IHDR and PNG oFFs chunks. Then I run a script "recrop.sh" to crop the original image according to those dimensions, scaled back up by 4x, and saving the result as PPM (which is lossless and gets rid of annoying metadata in the original JPEG). Here's my "recrop.sh" (GraphicsMagick-based) script:

    root=`echo $1 | sed -e "s/.png//"`
    
    gm identify $root.png
    string=`gm identify $root.png`
    
    echo string=$string
    
    resize_x=\
    `echo $string | sed -e "s/.* PNG //" -e "s/ Direct.*//" -e "s/x.*//"`
    
    resize_y=\
    `echo $string | sed -e "s/.* PNG [0-9]*x//" -e "s/+.*//"`
    
    offset_x=\
    `echo $string | sed -e "s/.* PNG [0-9x]*[0-9x]*+//" -e "s/+.*//"`
    
    offset_y=\
    `echo $string | sed -e "s/.* PNG [0-9x]*[0-9x]*+[0-9]*+//" -e "s/ .*//"`
    
    resize_x=`dc "-e $resize_x 4 * p"`
    resize_y=`dc "-e $resize_y 4 * p"`
    offset_x=`dc "-e $offset_x 4 * p"`
    offset_y=`dc "-e $offset_y 4 * p"`
    
    echo resize_x = $resize_x
    echo resize_y = $resize_y
    echo offset_x = $offset_x
    echo offset_y = $offset_y
    
    crop=$resize_x\x$resize_y+$offset_x+$offset_y
    
    echo crop geometry=$crop
    
    gm convert $root.JPG -crop $crop $root.ppm