【发布时间】:2019-06-29 22:24:35
【问题描述】:
我想将我的个人资料图片裁剪成正方形并减小它们的大小。所以我用谷歌搜索了“图像调整大小矩阵”。结果都不符合我的需要,所以我编写了自己的代码。它在 python/django 中。由于脖子和肩膀,我认为大多数头部图像的底部都有更多空间。所以我从顶部而不是从中间裁剪高度。所有的宽度都被裁剪到中间。它最多使用 300 个像素。我想这可能会帮助有类似任务的人。
我需要更多积分,这样我才能对内容进行投票。我整天都在使用该网站并得到很多答案,但我无法投票。这让我感到内疚。
from PIL import Image
class CustomUser(AbstractBaseUser, PermissionsMixin):
# User model fields, etc
image = models.ImageField(default='default.jpg',upload_to='profile_pics')
def save(self, *args, **kwargs):
super().save()
img = Image.open(self.image.path)
width, height = img.size # Get dimensions
if width > 300 and height > 300:
# keep ratio but shrink down
img.thumbnail((width, height))
width, height = img.size
# 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))
img.thumbnail((300, 300))
img.save(self.image.path)
elif width < height:
# make square by cutting off bottom
left = 0
right = width
top = 0
bottom = width
img = img.crop((left, top, right, bottom))
img.thumbnail((300, 300))
img.save(self.image.path)
else:
# already square
img.thumbnail((300, 300))
img.save(self.image.path)
elif width > 300 and height == 300:
left = (width - 300) / 2
right = (width + 300) / 2
top = 0
bottom = 300
img = img.crop((left, top, right, bottom))
img.save(self.image.path)
elif width > 300 and height < 300:
left = (width - height) / 2
right = (width + height) / 2
top = 0
bottom = height
img = img.crop((left, top, right, bottom))
img.save(self.image.path)
elif width < 300 and height > 300:
# most potential for disaster
left = 0
right = width
top = 0
bottom = width
img = img.crop((left, top, right, bottom))
img.save(self.image.path)
elif width < 300 and height < 300:
if height < width:
left = (width - height) / 2
right = (width + height) / 2
top = 0
bottom = height
img = img.crop((left, top, right, bottom))
img.save(self.image.path)
elif width < height:
height = width
left = 0
right = width
top = 0
bottom = height
img = img.crop((left, top, right, bottom))
img.save(self.image.path)
else:
img.save(self.image.path)
elif width == 300 and height > 300:
# potential for disaster
left = 0
right = 300
top = 0
bottom = 300
img = img.crop((left, top, right, bottom))
img.save(self.image.path)
elif width == 300 and height < 300:
left = (width - height) / 2
right = (width + height) / 2
top = 0
bottom = height
img = img.crop((left, top, right, bottom))
img.save(self.image.path)
elif width < 300 and height == 300:
left = 0
right = width
top = 0
bottom = width
img = img.crop((left, top, right, bottom))
img.save(self.image.path)
elif width and height == 300:
img.save(self.image.path)
【问题讨论】:
-
我建议您详细询问有关您的问题的适当问题,然后将问题的最后一部分(此代码)作为答案。
-
感谢您与我们分享您的代码,但您的代码写得不好,例如您将相同的条件块重复了 3 次,这是不必要的
标签: python django python-imaging-library crop image-resizing