imageyii2php-imagine

I need to calculate where to crop an image given x&y coordinates


I need to crop an image in the middle the original image on my application, to make the crop I need to provide the (x,y) coordinates, and that makes crop to start in the given coordinates.
So I understand in order to calculate x and y i need to apply the same calculation to both.
Please help me understand what I need to calculate the X coordinate to crop the image.

originalWidth = 1200   
newWidth = 600   
startCroopAt = ?

i.e. [x,y]

Image::crop(Yii::getAlias('@app/web/images/tmp/tmp_'.$name), $newWidth, $newHeight, [0,0])
        ->save(Yii::getAlias($path."/".$name), ['quality' => 80]);

Thanks for helping with this explanation.


Solution

  • startCroopAt = (originalWidth - newWidth) / 2

    newPosition = previousPosition + startCroopAt

    In a shor explanation, you should calculae the reduction index in order to calculate the new position, that is calculated by substracting the old with with the new width. Since the image cropping must be centered you will divide the index by two in order to simulate sort of a padding. With that the newPosition will be the displacement index starting from where the initial position before cropping was.

    When calculating the height it is the same procedure but in the y axis and width the new height.

    Hope this helps.

    Numeric Example would be.

    originalWidth = 1200   
    newWidth = 600   
    startCroopAt = (1200 - 600)/2 = 300
    newPosition = 0 + 300
    

    I guess previousPosition is the origin but in case there is an image displacement using previousPosition solves it.