Use Python to set image background color to transparent
Since the original logo has a white background, and we need to change the white background to transparent, here we use the versatile Python tool for image conversion, specifically the pillow package’s Image.
The PNG format has a fourth parameter in addition to the RGB colors that indicates the transparency of a pixel. For example, (0,0,0,0) means a transparent black. So during image conversion, we can convert that pixel to (0,0,0,0), and the following Python code achieves that.
Steps:
- Install the pillow package
- Define a function to convert the image background color to transparent PNG format
- Perform the image conversion
Install pillow package
First, install the pillow package using pip by running this command in the terminal:
pip install pillow
Define the function to convert image background to transparent PNG
The function takes the image file path as input and writes a transparent PNG file using the output name you pass in:
from PIL import Image
def transparent_png(imgfile, out="out"):
img = Image.open(imgfile)
img = img.convert("RGBA")
width, height = img.size
white_pixel = (255, 255, 255, 255)
for x in range(width):
for y in range(height):
if img.getpixel((x, y)) == white_pixel:
img.putpixel((x, y), (0, 0, 0, 0))
img.save(out + ".png")
Image conversion
Locally we have an image called “学会40周年图标.png” with a white background. We want to convert it to transparent background, so let’s start:
transparent_png("学会40周年图标.png", "40")
Check the effect before and after conversion:
Before:

After:

Summary
This article shows a simple way to replace a solid white background with transparent pixels using Pillow and save the result as PNG. For logos or other clean images with a uniform background, this direct pixel-by-pixel approach is usually enough.
- 原文作者:春江暮客
- 原文链接:https://www.bobobk.com/en/421.html
- 版权声明:本作品采用 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议 进行许可,非商业转载请注明出处(作者,原文链接),商业转载请联系作者获得授权。