如何仅调整django Imagefield中的宽度

如何仅调整django Imagefield中的宽度,django,python-3.x,django-models,Django,Python 3.x,Django Models,简介:我需要缩小我的个人资料图像中django图像的大小,使其宽度为300px,高度自动决定为与原始图片成比例。我如何使用下面的代码实现这一点 class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_image = models.ImageField(upload_to='profile_images/', default=''

简介:我需要缩小我的个人资料图像中django图像的大小,使其宽度为300px,高度自动决定为与原始图片成比例。我如何使用下面的代码实现这一点

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)        
    profile_image = models.ImageField(upload_to='profile_images/', default='', blank=True, null=True)

    def save(self, force_insert=False, force_update=False, using=None,
             update_fields=None):
        # Opening the uploaded image
        im = Image.open(self.profile_image)

        output = BytesIO()

        # Resize/modify the image
        im = im.resize((300, 250)) 
        #Here the width is 300 and height is 250. I want width to be 300 and height to be proportionately added. How do I modify the above code

        # after modifications, save it to the output
        im.save(output, format='JPEG', quality=100)
        output.seek(0)

        # change the imagefield value to be the newley modifed image value
        self.profile_image = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.profile_image.name.split('.')[0], 'image/jpeg',
                                        sys.getsizeof(output), None)

        super(Profile, self).save()
你可以这样做(根据答案):


只是一个简单的问题。如果我需要使宽度与高度成比例,是否可以将basewidth更改为baseheight是的,但计算结果会有点不同。比如
wpercent=(baseheight/(float(im.size[1])
wsize=int(float(img.size[0]*float(wpercent))
im = Image.open(self.profile_image)
output = BytesIO()
basewidth = 300
wpercent = (basewidth/float(im.size[0]))
hsize = int((float(img.size[1])*float(wpercent)))
im = im.resize((basewidth, hsize))