How can I create square thumbnails with Python and Wand? I'm trying to make square thumbnails from source images of any size. It's important that the thumbnail have the same aspect ratio as the original, cropping is ok, and it should fill the sapce of the thumbnail.
Asked
Active
Viewed 764 times
2 Answers
2
The following crop_center()
function makes the given image square.
from __future__ import division
from wand.image import Image
def crop_center(image):
dst_landscape = 1 > image.width / image.height
wh = image.width if dst_landscape else image.height
image.crop(
left=int((image.width - wh) / 2),
top=int((image.height - wh) / 2),
width=int(wh),
height=int(wh)
)
First you need to make the image square, and then you can resize()
the square smaller.

minhee
- 5,688
- 5
- 43
- 81
1
- No cropping.
- Fill the blank space with color (in this case: white).
- Maintain aspect ratio
from math import ceil
from wand.image import Color
def square_image(img):
width = float(img.width)
height = float(img.height)
if width == height:
return img
border_height = 0
border_width = 0
if width > height:
crop_size = int(width)
border_height = int(ceil((width - height)/2))
else:
crop_size = int(height)
border_width = int(ceil((height - width)/2))
img.border(color=Color('white'), height=border_height, width=border_width)
img.crop(top=0, left=0, width=crop_size, height=crop_size)
return img

Zoro-Alforque
- 81
- 1
- 5