0

I use weasyprint library in python to convert an HTML template to png. Then I am trying to convert the png image to jpg using a python library named PIL(PILLOW).

The PNG IMAGE is given below. enter image description here

But the image obtained after conversion using PIL is not what I was expecting. The colors are lost and only some components of the image are visible.

        from PIL import Image
        img = Image.open(file_path)
        rgb_im = img.convert('RGB')

        jpg_img_path = os.path.splitext(file_path)[0]
        jpg_img_path += '.jpg'
        rgb_im.save(jpg_img_path)

When I tried to use an online editor, they have provided me the perfect image from the png. Below is the jpg image obtained from the online converter. enter image description here

And the Image when I have used PIL. enter image description here

Amanpreet
  • 219
  • 3
  • 10

4 Answers4

2

The issue is that the original PNG image has an alpha layer, i.e. transparency, which JPEG doesn't support. The easiest thing to do is to make a new image the same size as the original image but filled with white, then paste the transparent image on top:

#!/usr/bin/env python3

from PIL import Image

# Open image
im = Image.open('image.png')

# Make a background, same size filled with solid white
result = Image.new('RGB', (im.width,im.height), color=(255,255,255))

# Paste original image over white background and save
result.paste(im,im)
result.save('result.jpg')

Thus just uses the same modules as you already have without introducing any new dependencies.

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
1

This could be completely wrong, but I suspect that what happens is that your HTML renderer gives you an alpha-channel PNG where the background is transparent, which then gets flattened to black by .convert(). If I am right, the problem should go away if you create an all-white image (or whatever background you prefer) of the same size as your PNG, and composite the PNG over that before convert() and save(). (There might be some smarter way of doing this that does not require you to actually create a complete background image, but this should do as a test).

Ture Pålsson
  • 6,088
  • 2
  • 12
  • 15
1

The answer of @Ture Palsson is correct, it is an alpha problem. You can try to get rid of it using some PIL workaround, as shown here, or you use some very simple skimage code, that I would prefer:

from skimage.io import imread, imsave
from skimage.color import rgba2rgb
png = imread('UCLgy.png')
imsave('UCLgy.jpg', rgba2rgb(png, (1,1,1))) # 1, 1, 1 is white
anki
  • 765
  • 5
  • 14
0

You can use the imgkit python library to convert HTML directly into png

Simdi
  • 794
  • 4
  • 13