【问题标题】:Rezise an image before uploading it with django在使用 django 上传之前调整图像大小
【发布时间】:2013-10-03 19:39:29
【问题描述】:

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

我使用 python 3.3 和 django 1.5。

我读到了 io.StringIO : 我不明白这篇文章的答案:Django resize image during upload 我不明白 io.StringIO 即使是那些explaination...

我也读过 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 

我有这个错误:

类型错误在

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

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

【问题讨论】:

  • 读取错误我猜问题是您在内存中调整图像大小。可能在 PIL 或 Pillow 文档中你会找到你的线索

标签: python django upload resize stringio


【解决方案1】:

如果你在 python 3.x 中使用 Django Rest Framework,这可能有用:

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

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

其次,现在你可以使用 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)

【讨论】:

    猜你喜欢
    • 2015-08-06
    • 2013-11-29
    • 2017-06-26
    • 2011-04-16
    • 2015-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多