1๐
โ
if you want to generate an image of resolution 300ร300, you have to crop() the image after generating thumbnail()
def save(self, *args, **kwargs):
super().save()
img = Image.open(self.header_image.path)
width, height = img.size # Get dimensions
print(f'Original Image Dimenstions: w:{width} h:{height}')
if width > 300 and height > 300:
# keep ratio but shrink down
img.thumbnail((width, height))
# check which one is smaller
if height < width:
# make square by cutting off equal amounts left and right
left = (width - height) / 2
right = (width + height) / 2
top = 0
bottom = height
img = img.crop((left, top, right, bottom))
elif width < height:
# make square by cutting off bottom
left = 0
right = width
top = 0
bottom = width
img = img.crop((left, top, right, bottom))
if width > 300 and height > 300:
img.thumbnail((300, 300))
width, height = img.size # Get new dimensions
print(f'Cropped Image Dimenstions: w:{width} h:{height}')
img.save(self.header_image.path)
๐คSumithran
Source:stackexchange.com