2016-07-14 54 views
0

我在做一個API,它從手機應用程序獲取圖像。圖像包含EXIF數據,其中一些圖像具有方向標籤(根據:PIL thumbnail is rotating my image?)。目前我解決了在命令行中使用imagemagick/morgify的問題。但是我想知道在DRF視圖中接收數據後是否可能(或者說是有意義的)使用PIL /枕頭自動定位。Django rest框架 - 使用PIL自動旋轉圖像

- 編輯 -

那樣子,我必須使用保存和刪除鉤子從http://www.django-rest-framework.org/api-guide/generic-views/

回答

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)