简体   繁体   中英

Rezise an image before uploading it with django

I would like to resize an image before uploading to reduce it weight.

I use python 3.3 and django 1.5.

I read about io.StringIO : I don't understand the answer of this post : Django resize image during upload I don't understand io.StringIO even with those explaination ...

I read about ajax too...

I was trying to do that :

image_field = form.cleaned_data.get('<myImageField>')
image_file = StringIO(image_field.read())
image = Image.open(image_file)
w, h = image.size
image = image.resize((w / 2, h / 2), Image.ANTIALIAS)
image_file = io.StringIO()
image.save(image_file, 'JPEG', quality=90)
image_field.file = image_file 

I have this error :

TypeError at

Can't convert 'InMemoryUploadedFile' object to str implicitly

Someone has a clue or a precise exemple to give me ?

If you are using Django Rest Framework with python 3.x, this might of use:

First define function to compress and resize image

def compress_image(photo):
# start compressing image
image_temporary = Image.open(photo)
output_io_stream = BytesIO()
# set here resize
image_temporary.thumbnail((1250, 1250), Image.ANTIALIAS)

# change orientation if necessary
for orientation in ExifTags.TAGS.keys():
    if ExifTags.TAGS[orientation] == 'Orientation':
        break
exif = dict(image_temporary._getexif().items())
# noinspection PyUnboundLocalVariable
if exif.get(orientation) == 3:
    image_temporary = image_temporary.rotate(180, expand=True)
elif exif.get(orientation) == 6:
    image_temporary = image_temporary.rotate(270, expand=True)
elif exif.get(orientation) == 8:
    image_temporary = image_temporary.rotate(90, expand=True)

# saving output
image_temporary.save(output_io_stream, format='JPEG', quality=75, optimize=True, progressive=True)
output_io_stream.seek(0)
photo = InMemoryUploadedFile(output_io_stream, 'ImageField', "%s.jpg" % photo.name.split('.')[0],
                             'image/jpeg', getsizeof(output_io_stream), None)
return photo

Second, now you can use the function in Serializers:

class SomeSerializer(serializers.ModelSerializer):
def update(self, instance, validated_data):
    # сжимаем рисунок
    if 'photo' in validated_data:           
        validated_data.update({'photo': compress_image(validated_data['photo'])})

    return super(SomeSerializer, self).update(instance, validated_data)

def create(self, validated_data):
    # сжимаем рисунок
    if 'photo' in validated_data:
        validated_data.update({'photo': compress_image(validated_data['photo'])})

    return super(SomeSerializer, self).create(validated_data)

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