Skip to content
Advertisement

Scale and crop an image in python PIL without exceeding the image dimensions

I am cropping an image using python PIL. Say my image is as such:

enter image description here

This is the simple code snippet I use for cropping:

JavaScript

The result of this is:

enter image description here

I want to scale out this cropped image keeping the aspect ratio (proportionate width and height) same by say 20% to look something like this without exceeding the image dimensions.

enter image description here

How should I scale out the crop such that the aspect ratio is maintained while not exceeding the image boundary/ dimensions?

Advertisement

Answer

You should calculate the center of your crop and use it there on. As an example:

JavaScript

In this way you will obtain the (x,y) point which corresponds to the center of your crop w.r.t your original image. In that case, you will know that the maximum width for your crop would be the minimum between the center value and the outer bounds of the original image minus the center itself:

JavaScript

Which gives you:

enter image description here

If you want to “enlarge” it to the maximum starting from the same center, then you will have:

JavaScript

which gives as a result, having the same center:

enter image description here


Edit

If you want to keep the aspect ratio you should retrieve it (the ratio) before and apply the crop only if the resulting size would still fit the original image. As an example, if you want to enlarge it by 20%:

JavaScript

Once you have the width and height values the process to get the crop is the same as above.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement