0

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

Ceres
  • 2,200
  • 1
  • 6
  • 22

2 Answers2

1

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).

Ceres
  • 2,200
  • 1
  • 6
  • 22
Daweo
  • 21,690
  • 3
  • 9
  • 19
  • I tried imghdr.what(None, h=img) and got 'jpeg'. – Ceres Jan 28 '21 at 08:57
  • Yeah, you were right. my config variable was messed up and converted to pdf in my main code. it didn't show up in testing. Thanks – Ceres Jan 28 '21 at 09:06
0

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")
Ceres
  • 2,200
  • 1
  • 6
  • 22