使用 Wand 读写上传的文件

Read and Write Uploaded File with Wand

这是我的代码:

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)

我收到错误:"no decode delegate for this image format `' @ 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)

已更新

我没用过 in a view years, but you should be able to create an InMemoryUploadedFile with StringIO. Example from 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)