0
votes

I am trying to convert an imgkit image into a PIL image to modify it. imgkit successfully converted the html to image when I tried to use a file. When I use BytesIO and try to convert to a PIL image, im getting an error.

Here is my code:

img = imgkit.from_string(template.render(a=elements, r=range(len(elements))), False, config=config)
bytesImg = BytesIO(img)
bytesImg.seek(0)
image = Image.open(bytesImg) #error here

PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x102082680>

I already saw this and this. Am I incorrectly converting the imgkit image to bytes or is there some other error?

Using Pillow 8.1 Python 3.9 and imgkit 1.0.2

2
What are the first 20 bytes of bytesImg please?Mark Setchell
@MarkSetchell . I used a print(bytesImg.read()) and got b'%PDF-1.4\n1 0 obj\n<<\n'. if that is what you are asking forCeres
That looks like a PDF which PIL can only write, not read pillow.readthedocs.io/en/stable/handbook/… Can you force ImgKit to generate a JPEG?Mark Setchell
Yeah, it worked. I messed up the config variable and it converted it to a pdf instead of image.Ceres

2 Answers

1
votes

Am I incorrectly converting the imgkit image to bytes or is there some other error?

I would start from checking if your bytes represents image understand by your Pillow. Built-in module imghdr should suffice if you are excepting one of format known by it (see table in docs). Usage in this case:

import imghdr

...

print(imghdr.what(None, h=img))

If it does identify format then check if it is supported by your Pillow, else you would need to manually check file signature (few starting bytes).

0
votes

imgkit was converting the html to pdf because the config variable was messed up.

use

which wkhtmltoimage

to find path to wkhtmltoimage and set

config = imgkit.config(wkhtmltoimage="path found")