Home > Software engineering >  Converting PNG to JPEG creates pixel noise in the background
Converting PNG to JPEG creates pixel noise in the background

Time:10-17

I have to convert some PNGs with transparent bg to simple JPEGs where the transparent background turns to white (which I assumed will happen by default). I have tried all of the solutions I could find here, but after saving the PNG as JPEG the image will look like this: (the noisy area was transparent on the PNG and the black was drop shadow)

Converted image

this is the converted image

Original image

enter image description here

This is the code I use:

# save the PNG 
response = requests.get(image_url, headers = header)
file = open("%s-%s.png" % (slug, item_id,), "wb")
file.write(response.content)
file.close()

# open the PNG and save as a JPEG
im1 = Image.open(filepath_to_png)
rgb_im = im1.convert('RGB')
rgb_im.mode
rgb_im.save(filepath_normal)

My question is that how could I prevent the JPEG to have that corrupted background? My goal is just simply have the same image in JPEG what I had in PNG.

CodePudding user response:

The method you are using to convert to RGB would work on some images that just require straight-forward conversion like the ones with hard-edged transparency masks, but for those with soft-edged masking (like the transparency shadows in your image) it is not be effective as the conversion does not know how to deal with that semi-transparency.

A better approach to handle this would be to create a new Image with the same dimensions and fill it with a white background, then you just need to paste your original image:

new_im = Image.new( "RGB", im1.size, ( 255,255,255 ) )
new_im.paste( im1, im1 )
new_im.save( filepath_normal )

I have tested this approach using an image with soft-edged masking and obtained the following Original png image

from PIL import Image
im = Image.open("1.png")
bg = Image.new("RGB", im.size, (255,255,255))
bg.paste(im,im)
bg.save("2.jpg")

Result I got had transparent background turned to white. Result jpg image

  • Related