0

Intro: I need to reduce the size of django images in my Profile Images such that the width is 300px and the height is decided automatically as proportionate to the original picture. How do I do that with my below code

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()
Samir Tendulkar
  • 1,151
  • 3
  • 19
  • 47

1 Answers1

1

You can do it like this(based on this answer):

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)) 
ruddra
  • 50,746
  • 7
  • 78
  • 101
  • Just a quick question. Can basewidth be changed with baseheight If I need to make the width proportionate to height – Samir Tendulkar Jan 05 '19 at 06:02
  • 1
    yes, but the calculations will be bit different. Like `wpercent = (baseheight/(float(im.size[1])` and `wsize=int(float(img.size[0]*float(wpercent))` – ruddra Jan 05 '19 at 06:05