How to make blog post images transparent

Posted by : on

Category : Others

Very often, we include images in our blog post to convey important messages, illustrate ideas, or simply to make the blog post more interesting. After all, the old adage says that a picture is worth a thousand words. However, what happens when the background color of the image does not blend in well with the color theme of your choice?

The answer is this discrepancy makes the article look inconsistent. The good news is that there is a quick fix.

Image processing

The fix is to use Python to convert (pixel by pixel) the background colour to transparent.

I use an image processing package called Pillow (https://python-pillow.org/) to handle different images. It detects the background pixel by checking if the Red, the Green and the Blue channels are 255. Then it sets the detected pixel to be (255,255,255, 0), where 0 means 100% transparency. Of course, it is also possible to set it to any other color that goes well with the theme of the site. Personally, getting rid of the background gives me less headache.

The rest of the script goes through the entire directory in which I store the images of the site and recreate the exact tree structure of the directories to store these newly converted images.

import os, time
from PIL import Image

def create_directories(root, tag):
    
    
    s = root[root.index(tag)+ len(tag):]

    # handle both windows or Unix systems
    sep = [ j for j, k in enumerate(s) if k == '/' or k == '\\']
    num_subfolders = len(sep)
    
    current_path = save_to
    
    for i, sub in enumerate(sep):
        if num_subfolders == 1 or i == num_subfolders - 1 :
            start_index = sub + 1
            end_index = len(s)
            
       
        else:
            start_index = sub + 1
            end_index = sep[i+1]
            
        current_path = os.path.join(current_path, s[start_index:end_index])
            
            
        if not os.path.exists(current_path):
            os.mkdir(current_path)
                
    return current_path

for root, dirs, files in os.walk(source_from):
    
    for file in files:
        if file.endswith('.png'):
            print ('image file: ', file)
            path = os.path.join(root, file)
            print ('image path : ', path )
            
            img = Image.open(path)
            
            width = img.size[0]
            height = img.size[1]
            
            for x in range(0,width):
                for y in range(0, height):
                    data = img.getpixel((x,y))
                    if (data[0] == 255 and data[1] == 255 and data[2] == 255):
                        # 0 = 100% transparent
                        img.putpixel((x,y), (255,255,255, 0))
                        
            current_path = create_directories(root, tag)
            print ('current path : ', current_path)          
            
                        
            img.save(os.path.join(current_path, file))

My other blog posts contain many examples of images (after conversion) with a transparent background. Please feel free to check them out on this site.

About

Hello, My name is Wilson Fok. I love to extract useful insights and knowledge from big data. Constructive feedback and insightful comments are very welcome!