I want to crop my images but keep the size or the aspect ratio fixed. Right now when I am adding the parameter, it is removing parts of my image in the output. I want the full image to be preserved and aspect ratio to remain fixed. How to achieve this in ImageKit?
I want to crop my images but keep the size or the aspect ratio fixed. Right now when I am adding the parameter, it is removing parts of my image in the output. I want the full image to be preserved and aspect ratio to remain fixed. How to achieve this in ImageKit?
There are a few ways to do this in ImageKit to ensure that while resizing the image is not cropped or the aspect ratio does not get changed.
Why cropping happens
When you specify both the height and width dimensions while resizing the image, then ImageKit defaults to matching both the dimensions you specify. This means, if the input image’s aspect ratio was different from the resize you request, then the input image gets cropped to match the output size.
For example, if this is my input image (slightly rectangular with width > height)
https://ik.imagekit.io/ikmedia/docs_images/example_image.jpg
And I resize this to 300x300 (Square), we can see that parts around the image get cropped
https://ik.imagekit.io/ikmedia/docs_images/example_image.jpg?tr=w-300,h-300
Method 1 - Specify only one of the resizing dimensions, height or width
To avoid cropping, specify only one of the resizing dimensions, and let ImageKit calculate the other to prevent cropping or change in aspect ratio.
For example
https://ik.imagekit.io/ikmedia/docs_images/example_image.jpg?tr=w-300
The image is now 300px wide, but the height is at 200px (calculated automatically)
Method 2 - Use at_max crop mode
If your requirement does not allow you to specify only one dimension, for example, you always want the image to fit inside a fixed size box, then you can additionally add the c-at_max crop mode to the URLs. This crop mode ensures no cropping, preserves the aspect ratio, and ensures that the maximum resolution is capped at the height and width you specify.
https://ik.imagekit.io/ikmedia/docs_images/example_image.jpg?tr=w-300,h-300,c-at_max
Method 3 - Pad the image
If the input and output aspect ratios, do not match, then instead of cropping, we can also go for padding to match the output aspect ratio but not have to crop out the image.
For example, the image below is padded using cm-pad_resize parameter.
https://ik.imagekit.io/ikmedia/docs_images/example_image.jpg?tr=w-300,h-300,cm-pad_resize,bg-grey
The output image size is now 300x300, and the image is not cropped at all.
I have intentionally added bg-grey to show a background color where padding is being added. You can omit it completely to retain a white background, or use
bg-blurred
to use a blurred image as a background.
https://ik.imagekit.io/ikmedia/docs_images/example_image.jpg?tr=w-300,h-300,cm-pad_resize,bg-blurred