'Converting Image from RGBA to RGB reveals padding, how to crop that?
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:
Solution 1:[1]
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")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |