在我的models.py中,我得到了一个名为Post的类和一个名为postcover的ImageField。我想将所有图像保存为PNG格式,到目前为止效果还不错,但是我不知道在处理完图像后如何保持实际的图像纵横比。
使用以下解决方案时,出现以下错误:
'int'对象不可下标
models.py
class Post(models.Model):
...
postcover = fields.ImageField(
verbose_name="Post Cover",
blank=True,
null=True,
upload_to=get_file_path_user_uploads,
validators=[default_image_size, default_image_file_extension]
)
...
def save(self, *args, **kwargs):
super(Post, self).save(*args, **kwargs)
if self.postcover:
if os.path.exists(self.postcover.path):
imageTemproary = Image.open(self.postcover)
outputIoStream = BytesIO()
baseheight = 500
hpercent = (baseheight / float(self.postcover.size[1]))
wsize = int((float(self.postcover.size[0]) * float(hpercent)))
imageTemproaryResized = imageTemproary.resize((wsize, baseheight))
imageTemproaryResized.save(outputIoStream, format='PNG')
outputIoStream.seek(0)
self.postcover = InMemoryUploadedFile(outputIoStream, 'ImageField',
"%s.png" % self.postcover.name.split('.')[0], 'image/png',
sys.getsizeof(outputIoStream), None)
super(Post, self).save(*args, **kwargs)
完整跟踪:
Internal Server Error: /post/2/edit/
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/app/app_Accounts/decorators.py", line 33, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/ratelimit/decorators.py", line 30, in _wrapped
return fn(*args, **kw)
File "/app/app/views.py", line 473, in post_edit
post.save()
File "/app/app/models.py", line 204, in save
hpercent = (baseheight / float(self.postcover.size[1]))
TypeError: 'int' object is not subscriptable
首先感谢您的帮助:)
答案 0 :(得分:2)
您正在尝试将文件大小视为具有宽度和高度的元组。您想使用imageTemproary.size
而不是self.postcover.size
:
hpercent = baseheight / imageTemproary.size[1]
wsize = int(imageTemproary.size[0] * hpercent)
我也简化了代码,您使用的是Python 3,即使输入都是整数(真除法,也不是底数除法),/
也会产生浮点值。
您可能需要更正图像对象变量(imageTemporary
)的拼写;我个人只是使用image
。