gpt4 book ai didi

python - 使用 Wand 读取和写入上传的文件

转载 作者:太空宇宙 更新时间:2023-11-03 14:25:02 26 4
gpt4 key购买 nike

这是我的代码:

class ToPng(APIView):
def post(self, request, *args, **kwargs):

revision = request.data.get('revision', None)
file = request.data.get('file', None)

with tempfile.TemporaryFile() as tmp:
tmp.write(file.read())
all_pages = Image(file=tmp)
single_image = all_pages.sequence[0]
with Image(single_image) as img:
img.format = 'png'
img.background_color = Color('white')
img.alpha_channel = 'remove'
MyModel.objects.create(revision=revision, file=img)
return Response(HTTP_200_OK)

我收到错误:“此图像格式没有解码委托(delegate)`'@ error/blob.c/BlobToImage/353”

显然我犯了一个严重的错误,因为安装了 imagemagick 和 Ghostscript 的 wand 可以立即将 Pdf 转换为 Png。我可能读错了,但我不知道还能做什么。

最佳答案

您只需在读取之前将临时文件重置回文件开头即可。

    with tempfile.TemporaryFile() as tmp:
tmp.write(file.read())
tmp.seek(0)
all_pages = Image(file=tmp)

已更新

我没用过在 View 年中,但您应该能够使用 StringIO 创建一个 InMemoryUploadedFile。示例来自here

import StringIO
# ... Skip to after img work ...
img_io=StringIO.StringIO()
img.save(file=img_io)
img_file=InMemoryUploadedFile(img_io,
None,
'first_page.jpg',
'image/jpeg',
img_io.len,
None)
MyModel.objects.create(revision=revision, file=img_file)

关于python - 使用 Wand 读取和写入上传的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47697473/

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