我正在尝试将 Pillow 图像转换为 Django ImageField。
基本上,我:
- 获取
ImageField
作为输入(来自用户提交的表单) - 使用
Pillow
打开它 - 处理它(在这种情况下模糊它)
- 将其传回我的 Django 表单
- 尝试保存表单⚠️
这是最后一步,我遇到错误 'Image' object has no attribute '_committed'
(我认为 Django 无法保存 Pillow 图像并且需要对其进行转换)
def upload_media(request):
if request.method == 'POST':
form = PostForm(request.POST, request.FILES)
if form.is_valid():
image = form.cleaned_data['image']
pil_image = Image.open(image)
blurred_image = pil_image.filter(ImageFilter.GaussianBlur(100))
post = Post(image=image, blurred_image=blurred_image)
post.save()
return redirect('index')
最佳答案
在 django 文件中,请求中的数据转换为 fileupload 对象。您需要获取此图像并将其转换为字节,然后使用 InMemoryUploadedFile 类将其转换为 fileupload 对象。该类的输出是 fileupload 对象。
image = Img.open(field)
image = image.convert('RGB')
image = image.resize((800, 800), Img.ANTIALIAS)
output = io.BytesIO()
image.save(output, format='JPEG', quality=85)
output.seek(0)
new_pic= InMemoryUploadedFile(output, 'ImageField',
field.name,
'image/jpeg',
sys.getsizeof(output), None)
关于django - 将 Pillow 图像转换为 Django ImageField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55025387/