0

I'm trying to convert an image from RGBA to RGB. But the conversion to RGB is adding padding to the image. How can I convert without the padding? Or how can I remove it?

    img = Image.open('path.png')
    img.save("img.png")
    
    rgb_im = img.convert('RGB')
    rgb_im.save("rgb_im.png")

Thank you. Images below, before and after conversion:

enter image description here

enter image description here

Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36
stracc
  • 507
  • 1
  • 4
  • 10
  • 1
    You aren't showing any images! I can only guess the alpha channel is doing something unexpected. Maybe try cropping to the alpha channel https://stackoverflow.com/a/63244423/2836621 – Mark Setchell May 04 '22 at 11:00
  • 3
    It's not padding, you're just removing transparency from the frame, so you get it white instead of transparent. You should crop your image. – David May 04 '22 at 11:26

1 Answers1

2

If you open your first image, you'll see that the canvas is larger than the visible image, as you have a transparent frame represented by pixels having rgba=(255,255,255,0). When you remove the alpha channel by converting RGBA to RGB, that transparency disappear, as only rgb=(255,255,255) remains, which turns out to be the white you see in the second image.

So you want to make something similar to what's suggested here

from PIL import Image, ImageChops

def trim_and_convert(im):
    bg = Image.new(im.mode, im.size, (255,255,255,0))
    diff = ImageChops.difference(im, bg)
    diff = ImageChops.add(diff, diff, 2.0, -100)
    bbox = diff.getbbox()
    if bbox:
        return im.crop(bbox).convert('RGB')

im = Image.open("path.png")

rgb_im = trim_and_convert(im)
rgb_im.save("rgb_im.png")
David
  • 513
  • 7
  • 26