繁体   English   中英

在使用django上传图像之前先对其进行大小调整

[英]Rezise an image before uploading it with django

我想在上传之前调整图像大小以减轻其重量。

我使用python 3.3和django 1.5。

我读到有关io.StringIO的信息:我不明白这篇文章的答案: 在上传过程中Django调整图像大小我什至不理解io.StringIO的解释 ...

我也读过有关Ajax的文章...

我正在尝试这样做:

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 

我有这个错误:

TypeError在

无法将'InMemoryUploadedFile'对象隐式转换为str

有人有线索或确切的例证要给我吗?

如果您将Django Rest Framework与python 3.x一起使用,则可能会使用:

首先定义函数来压缩和调整图像大小

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

其次,现在您可以在序列化器中使用该功能:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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