我正在尝试在保存之前调整大小/转换上传的图像:
def resize_convert(image_file, size, file_full_name):
os.chdir(BASE_DIR + '/convert/')
file_name = os.path.splitext(os.path.basename(file_full_name))[0]
file_ext = os.path.splitext(os.path.basename(image_file))[1]
files = {}
for i in size:
cmd = ['convert', image_file, '-resize', i, file_name + i + file_ext]
subprocess.check_call(cmd, shell=False)
webp_cmd = ["cwebp", "-q", "100", file_name + i + file_ext, "-o", file_name + '_' + i + '.webp']
subprocess.check_call(webp_cmd)
files[i] = os.getcwd() + '/' + file_name + '_' + i + '.webp'
return files
所以从视图中我通过了所有必要的参数,如下所示:
for pro in product_files:
resize_convert(pro.file.name, ["308x412"], pro)
然后引发此错误
expected str, bytes or os.PathLike object, not TemporaryUploadedFile
更新:
def resize_convert(_image_file, size, file_full_name):
image_file = _image_file.temporary_file_path()
os.chdir(BASE_DIR + '/convert/')
file_name = os.path.splitext(os.path.basename(file_full_name))[0]
file_ext = os.path.splitext(os.path.basename(image_file))[1]
....
错误:
File "/home/.../image.py", line 17, in resize_convert
image_file = _image_file.temporary_file_path()
AttributeError: 'str' object has no attribute 'temporary_file_path'
ERROR:django.request: Internal Server Error: /admin/product/update/7/ (22-06-2019 23:26:21; log.py:228)
Traceback (most recent call last):
File "/home/../.env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/../.env/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/.../.env/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/../.env/lib/python3.6/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/home/.../views.py", line 562, in product_update
resize_convert(pro.file.name, ["308x412"], pro)
File "/home/..utils/image.py", line 17, in resize_convert
image_file = _image_file.temporary_file_path()
AttributeError: 'str' object has no attribute 'temporary_file_path'
答案 0 :(得分:0)
这里的问题是,传递给函数的from time import sleep
string = "hello world"
words = string.split(' ') # splits the string into parts divided by ' '
for w in words:
print(w, end=' ')
sleep(0.1) #delays for 0.1 seconds
是一个image_file
对象。您不能将对象传递给子流程。
您需要为其提供文件路径。
TemporaryUploadedFile
上面的方法应该起作用,但是我建议使用def resize_convert(image_file, size, file_full_name):
image_file_path = image_file.temporary_file_path()
# ...
进行图像处理。那是一个python库,您不需要使用子进程。
参见示例:How do I resize an image using PIL and maintain its aspect ratio?