There are a number of algorithms to crop and resize images. Like maintaining the original image’s aspect ratio, cropping over-sized images, padding to fill empty area.
This post shows two approaches – with cropping and without cropping.
Approach 1. Resizing without cropping.
// see the method resize_with_nocrop
If an original image has different proportions than the desired image, then a part of image might be cropped.
Note that in this approach the final size of the image can be not exactly the same as we asked.
It will happen in case when the original aspect ration differs from the desired aspect ratio.
For example, if the size of the original image is 149×200 and we want to resize to 300×400, then the result image will have the size 298×400, i.e. NOT 300×400 as we asked.
Approach 2. Resizing image to get a fixed (exact) size (with cropping)
// see the method resize_crop
This approach will be useful if we need the result image to have fixed size and we don’t want to distort image or pad some area with background color. Then we have to crop a small part of image if the original aspect ratio is different from the needed aspect ratio.
The idea is to magnify an image maintaining the aspect ratio to make the width (or height, depending on the aspect ration) as needed for the final image. After this operation the height (or width) will be bigger then the desired, so we can crop that part which is over the limit.
This approach guarantees that the image will not be distorted because of scaling, but a part of image might be cropped.