We will be working with the following image:
https://cdn.ixmage.com/v2/grappler/images/demo/wall.jpg?w=300&h=225&bgc=lime
This image is shown at 300x225 dimensions, but its natural/original size is 1200x900 pixels.
There are 2 ways to do some image cropping, and the method will be selected based on the use case.
For this method, the image original dimensions are essential to determining the transformation values.
&crop=width,height,x,y
The crop
transformation requires 4 integer values:
value | description |
---|---|
width | The width of the portion of the original image we want crop |
height | The height of the portion of the original image |
x | An x offset (to the right of the top-left corner of the original image) to start our cropping |
y | A y offset (going down from the top-left corner of the original image) to start cropping |
Let’s jump into a cropping example using the sample image.
We want to crop the area shown below:
We need to come up with the values for the crop
transformation, and we will use the above aid as guidance.
The above image aid is the 300x225 version of the original source image. For the desired cropped area, I have determined that w
is 120 pixels, and h
is 150 pixels. These values need to be converted to measures for the original dimensions which are 1200x900.
1200 to 300 is a ratio of 4.
This means w
should be 480 (120 * 4) and h
should be 600.
&crop=480,600,x,y
Now we will take a look at the values to offset from the top-left corner of the image.
x
is 40 and y
is 45 for the 300px wide version. Times a ratio of 4 gives us 160,180
&crop=480,600,160,180
On this cropping method, the crop occurs on the original image before resizing takes place.
This is why the crop
values need to comply with the original image dimensions, so we get back the expected area.
Because we left the parameters w=300&h=225
in the image url, the cropped piece was then resized to those requested dimensions.
Here is the image without a set width:
https://cdn.ixmage.com/v2/grappler/images/demo/wall.jpg?h=225&bgc=lime&crop=480,600,160,180
Sometimes it could be easier to work with an already resized image, and then apply cropping.
For this method, we use transformation crop2
Let’s see a crop where we use the values from the 300px version:
&crop2=120,150,40,45
> results 120x150
On this method, the crop2
values are related to our w
and h
values. Changing a dimension like width and not changing the crop value(s) may result in an unexpected crop.
The resulting dimensions from a crop2
will be the crop’s with and height.