我正在将一些图像加载到Django模型中。
当我通过Django模板显示这些图像时,纵向图像会旋转。如果我通过Django Admin查看这些相同的图像,点击它们显示的链接,就像我期望的那样。
这是我加载图片的观点:
def upload_profile(request, user_id):
variables = {}
if request.POST:
user_form = UserForm(request.POST, instance=User.objects.get(id=request.user.id))
myuser_form = MyUserForm(request.POST, request.FILES, instance=MyUser.objects.get(user__id=request.user.id))
if user_form.is_valid() and myuser_form.is_valid():
user_form.save()
myuser = myuser_form.save()
myuser.photo = apply_orientation(myuser.photo)
myuser.save()
return game_selection(request)
variables['user_form'] = user_form
variables['myuser_form'] = myuser_form
return render(request, 'esc/profile.html', variables)
这就是我应用轮换的方式:
def flip_horizontal(im): return im.transpose(Image.FLIP_LEFT_RIGHT)
def flip_vertical(im): return im.transpose(Image.FLIP_TOP_BOTTOM)
def rotate_180(im): return im.transpose(Image.ROTATE_180)
def rotate_90(im): return im.transpose(Image.ROTATE_90)
def rotate_270(im): return im.transpose(Image.ROTATE_270)
def transpose(im): return rotate_90(flip_horizontal(im))
def transverse(im): return rotate_90(flip_vertical(im))
orientation_funcs = [None,
lambda x: x,
flip_horizontal,
rotate_180,
flip_vertical,
transpose,
rotate_270,
transverse,
rotate_90
]
def apply_orientation(im):
"""
Extract the oritentation EXIF tag from the image, which should be a PIL Image instance,
and if there is an orientation tag that would rotate the image, apply that rotation to
the Image instance given to do an in-place rotation.
:param Image im: Image instance to inspect
:return: A possibly transposed image instance
"""
try:
kOrientationEXIFTag = 0x0112
if hasattr(im, '_getexif'): # only present in JPEGs
e = im._getexif() # returns None if no EXIF data
if e is not None:
#log.info('EXIF data found: %r', e)
orientation = e[kOrientationEXIFTag]
f = orientation_funcs[orientation]
return f(im)
except:
# We'd be here with an invalid orientation value or some random error?
pass # log.exception("Error applying EXIF Orientation tag")
return im
我的代码似乎永远不会通过条件if hasattr(im, '_getexif'):
****编辑****
所以它没有通过,因为无论我加载什么图像,都没有' _getexif'。
如果我添加print getattr(im, '_getexif')
,我会收到以下错误,包含所有图片
' ImageFieldFile'对象没有属性' _getexif'