Reputation: 2947
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.
Upvotes: 2
Views: 1761
Reputation: 334
I have used the [Imagine] image library to more easily accomplish image cropping. I like it because it is file-type agnostic and supports transparent PNGs. This function also resizes the image with the specified width and height.
$cropheight = $bottom - $top;
$cropwidth = $right - $left;
$target = "./images/cropped/";
$imagine->open($path)
->crop(new Point($top, $left), new Box($cropheight,$cropwidth))
->resize(new Box($width, $height))
->save($target);
I define the most important parameters used while cropping. I am using an image approx 1000x1000 and would like to crop roughly in the center of it.
$uri="http://./smile.jpg";
$top = 90;
$left = 40;
$bottom = 800;
$right = 500;
$width = 920;
$height = 500;
Upvotes: 1
Reputation: 80
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.
Upvotes: 3