保存在Django中之前如何旋转图像?

时间:2018-08-09 09:31:15

标签: python django django-rest-framework python-imaging-library

现在,我正在创建一个Web应用程序,该应用程序允许用户使用Django Rest Framework上传图像。 我想根据EXIF标签旋转这些图像并保存。

最初,我发现了this way,它可以在本地环境中工作。 但是,现在我使用Amazon S3进行部署,所以这种方式行不通。

因此,我正在尝试旋转图像,然后再进行保存和苦苦挣扎...下面的最新代码在发布新的Work对象时引发TypeError at /api/work/ 'str' object is not callable

如何修复?
还是还有其他好方法?

[models.py]

from django.db import models
from django.conf import settings
from PIL import Image as Img
from PIL import ExifTags
from io import BytesIO
from django.core.files import File
import datetime


class Work(models.Model):
    owner       = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True)
    title       = models.CharField(max_length=120)
    made_date   = models.DateField(default=datetime.date.today, null=True, blank=True)
    note        = models.TextField(max_length=2000, null=True, blank=True)
    image       = models.ImageField(upload_to='work_pic', default='default_image.png')

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        if self.image:
            pilImage = Img.open(BytesIO(self.image.read()))
            for orientation in ExifTags.TAGS.keys():
                if ExifTags.TAGS[orientation] == 'Orientation':
                    break
            exif = dict(pilImage._getexif().items())

            if exif[orientation] == 3:
                pilImage = pilImage.rotate(180, expand=True)
            elif exif[orientation] == 6:
                pilImage = pilImage.rotate(270, expand=True)
            elif exif[orientation] == 8:
                pilImage = pilImage.rotate(90, expand=True)

            output = BytesIO()
            pilImage.save(output, format='JPEG', quality=75)
            output.seek(0)
            self.image = File(output, self.image.name())

        return super(Work, self).save(*args, **kwargs)

[serializers.py]

from rest_framework import serializers
from .models import Work


class WorkSerializer(serializers.ModelSerializer):
    owner = serializers.HiddenField(default=serializers.CurrentUserDefault())

    class Meta:
        model = Work
        fields = '__all__'

    def create(self, validated_data):
        return Work.objects.create(**validated_data)

1 个答案:

答案 0 :(得分:2)

在您的 save() 方法中,您正在调用 self.image.name 属性作为函数。 Image.namestring属性,因此您不必将其作为函数来调用。

所以换行 self.image = File(output, self.image.name())
self.image = File(output, self.image.name)
将解决错误

完整的模型定义

class Work(models.Model):
    owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True)
    title = models.CharField(max_length=120)
    made_date = models.DateField(default=datetime.date.today, null=True, blank=True)
    note = models.TextField(max_length=2000, null=True, blank=True)
    image = models.ImageField(upload_to='work_pic', default='default_image.png')

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        if self.image:
            pilImage = Img.open(BytesIO(self.image.read()))
            for orientation in ExifTags.TAGS.keys():
                if ExifTags.TAGS[orientation] == 'Orientation':
                    break
            exif = dict(pilImage._getexif().items())

            if exif[orientation] == 3:
                pilImage = pilImage.rotate(180, expand=True)
            elif exif[orientation] == 6:
                pilImage = pilImage.rotate(270, expand=True)
            elif exif[orientation] == 8:
                pilImage = pilImage.rotate(90, expand=True)

            output = BytesIO()
            pilImage.save(output, format='JPEG', quality=75)
            output.seek(0)
            self.image = File(output, self.image.name)

        return super(Work, self).save(*args, **kwargs)