Welcome!
This is the community forum for my apps Pythonista and Editorial.
For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.
Sharing for the beginners like me: Transparent Background
-
While trying to figure this out for myself, I read a few threads in this forum that touched on this topic. I figured I would share this to help out other newbies like myself who are just starting to learn the basics of python. I made very slight adjustments to the code from the following link:
https://www.science-emergence.com/Articles/How-to-make-background-image-transparent-using-python/
The aim for this person was to make the white background transparent and make the black lettering sharper.
My goal was to take any color background and make it transparent so it could be used for a spritesheet for games. This is what I ended up with:from PIL import Image img = Image.open('image.png') img = img.convert("RGBA") # RGBA means Red, Green, Blue, Alpha. Alpha is the transparency of the image. datas = img.getdata() rgb = datas[0] #get the color of the first pixel of the image, in RGB format newData = [] for item in datas: if item[0] == rgb[0] and item[1] == rgb[1] and item[2] == rgb[2]: #check if the pixel matches the first pixel's color newData.append((0, 0, 0, 0)) #set the pixel to black and make it transparent. the first three numbers are the RGB levels and the fourth is the alpha else: newData.append(item) img.putdata(newData) img.save("image_transparent.png", "PNG")
Basically it sets the first pixel in the very top left as the background color and then goes through every pixel of the image and if the color of the pixel is the same as the first pixel, it makes it transparent. If the first pixel of the image is not the background color, you can set the number in datas[0] to whichever pixel you want to establish as the background color.
I take no credit for writing any of this code since I just made very very minor adjustments to someone else's code, and just added a few comments. I am just sharing this because I appreciate it when I get help from others:)