春江暮客

春江暮客的个人学习分享网站

Use Python to set image background color to transparent

2020-01-12 Technology
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:

  1. Install the pillow package
  2. Define a function to convert the image background color to transparent PNG format
  3. 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:
png_before

After:
png_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.

友情链接

其它