简体   繁体   中英

Resize image before upload django without saving

I am trying to crop and resize before uploading image, here is spinnet of my code -

            x,y,w,h = self.x, self.y, self.w, self.h
            image = Image.open(self.cleaned_data.get('profile_image'))
            try:
                for orientation in ExifTags.TAGS.keys() :
                    if ExifTags.TAGS[orientation]=='Orientation' : break
                exif=dict(image._getexif().items())
                if exif[orientation] == 3 :
                    image=image.rotate(180, expand=True)
                elif exif[orientation] == 6 :
                    image=image.rotate(270, expand=True)
                elif exif[orientation] == 8 :
                    image=image.rotate(90, expand=True)
            except:
                pass
            cropped_image = image.crop((x, y, w+x, h+y))
            resized_image = cropped_image.resize((160, 160), Image.ANTIALIAS)
            filename = 'image'
            new_image = InMemoryUploadedFile(resized_image,'ImageField',\
                            "%s.jpg" % filename , 'image/jpeg', resized_image.__sizeof__(), None)
            self.cleaned_data['profile_image'] = resized_image
            return super(UpdateUserProfileForm, self).save()

this is not working, resized image is not saved instead original get saved. I have to save it in InMemoryUploadedFile because I am using AWS S3 bucket for media files and it doesn't support absolute path for saving images.

Previously in development I am using this code -

            x,y,w,h = self.x, self.y, self.w, self.h
            try:
                image = Image.open(update_form.profile_image)
                for orientation in ExifTags.TAGS.keys() :
                    if ExifTags.TAGS[orientation]=='Orientation' : break
                exif=dict(image._getexif().items())
                if exif[orientation] == 3 :
                    image=image.rotate(180, expand=True)
                elif exif[orientation] == 6 :
                    image=image.rotate(270, expand=True)
                elif exif[orientation] == 8 :
                    image=image.rotate(90, expand=True)
            except:
                pass
            cropped_image = image.crop((x, y, w+x, h+y))
            resized_image = cropped_image.resize((160, 160), Image.ANTIALIAS)
            resized_image.save(update_form.profile_image.path)

This was working fine but I need to change the code because resized_image.save(update_form.profile_image.path) is giving error that backend doesn't support absolute path.

To alter the cleaned_data use method clean_<attibute> like -

def clean_profile_image(self):
        if 'profile_image' in self.changed_data:
            p_image = self.cleaned_data.get('profile_image')
            print('self.cleaned_data',p_image)
            x,y,w,h = self.x, self.y, self.w, self.h
            image = Image.open(p_image)
            try:
                for orientation in ExifTags.TAGS.keys() :
                    if ExifTags.TAGS[orientation]=='Orientation' : break
                exif=dict(image._getexif().items())
                if exif[orientation] == 3 :
                    image=image.rotate(180, expand=True)
                elif exif[orientation] == 6 :
                    image=image.rotate(270, expand=True)
                elif exif[orientation] == 8 :
                    image=image.rotate(90, expand=True)
            except:
                pass
            cropped_image = image.crop((x, y, w+x, h+y))
            resized_image = cropped_image.resize((160, 160), Image.ANTIALIAS)
            filename = 'image'
            output = StringIO()
            resized_image.save(output, format='JPEG', quality=95)
            output.seek(0)
            new_image = InMemoryUploadedFile(output,'ImageField',\
        "%s.jpg" % filename , 'image/jpeg', resized_image.__sizeof__(), None)
            print('new_image',new_image)
            return new_image

also to initialize x,y,w,h in init -

def __init__(self,*args,**kwargs):
        print(args)
        print(kwargs)
        if kwargs.get('data'):
            self.x = float(kwargs.get('data').get('x'))
            self.y = float(kwargs.get('data').get('y'))
            self.w = float(kwargs.get('data').get('width'))
            self.h = float(kwargs.get('data').get('height'))
            print(self.x,self.y,self.w,self.h)
        return super(UpdateUserProfileForm,self).__init__(*args,**kwargs)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM