我正在做一个API,它从手机应用程序中获取图像。图像包含EXIF数据,其中一些图像具有方向标记(根据:PIL thumbnail is rotating my image?)。目前我解决了在命令行中使用imagemagick / morgify的问题。但我想知道在DRF视图中接收数据后,是否有可能(或有意义)使用PIL / Pillow进行自动定位。
- 编辑 -
看起来,我必须使用http://www.django-rest-framework.org/api-guide/generic-views/
中的保存和删除挂钩答案 0 :(得分:0)
好的,所以代码是(从PIL thumbnail is rotating my image?复制的自动旋转代码):
from PIL import Image, ExifTags
def autorotate(path):
""" This function autorotates a picture """
image = Image.open(path)
if hasattr(image, '_getexif'): # only present in JPEGs
orientation = None
for orientation in ExifTags.TAGS.keys():
if ExifTags.TAGS[orientation] == 'Orientation':
break
e = image._getexif() # returns None if no EXIF data
if e is not None:
exif = dict(e.items())
orientation = exif[orientation]
if orientation == 3:
image = image.transpose(Image.ROTATE_180)
elif orientation == 6:
image = image.transpose(Image.ROTATE_270)
elif orientation == 8:
image = image.transpose(Image.ROTATE_90)
image.save(path)
class ReceivedDataList(generics.ListCreateAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
filter_backends = (filters.DjangoFilterBackend,)
filter_class = UserFilter
def perform_create(self, serializer):
instance = serializer.save()
autorotate(instance.photo.file.name)