1

Here is my code:

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)

I get the error: "no decode delegate for this image format `' @ error/blob.c/BlobToImage/353"

Obviously I am making a grave mistake since wand, with imagemagick and ghostscript installed, can convert Pdf to Png right away. I am probably reading the wrong thing but I don't know what else to do.

Ali Ankarali
  • 2,761
  • 3
  • 18
  • 30

1 Answers1

1

You just need to reset the tempfile back to the beginning of the file before reading.

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

Updated

I haven't used 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)
emcconville
  • 23,800
  • 4
  • 50
  • 66