gpt4 book ai didi

python - 图像在 Django 模板中旋转

转载 作者:行者123 更新时间:2023-11-30 22:37:35 24 4
gpt4 key购买 nike

我正在将一些图像加载到 Django 模型中。

当我通过 Django 模板显示这些图像时,肖像图像会旋转。如果我通过 Django Admin 通过单击它们按预期显示的链接来查看这些相同的图像。

这是我加载图像的 View :

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' object has no attribute '_getexif'

最佳答案

所以我删除了上面的所有代码并用以下代码替换

from imagekit.models import ImageSpecField
from imagekit.processors import ResizeToFill, Transpose, SmartResize

class MyUser(models.Model):
avatar = models.ImageField(upload_to='upload/avatars', max_length=255, blank=True, null=True)
avatar_thumbnail = ImageSpecField(
source='avatar',
processors = [Transpose(),SmartResize(200, 200)],
format = 'JPEG',
options = {'quality': 75}
)

有效

关于python - 图像在 Django 模板中旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43841223/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com