Author: Wu Haichao

Personal website: www.wuhaichao.com

Recently, due to the special needs of the project, the theme color is always changed, and the main color of some icon pictures in the APP also needs to be changed. The artist can only rely on himself without providing cutting images. At first, he tried to find the images on iconfont, but the quantity is too much, which is a waste of time. Then I realized that Python’s Pillow is very powerful for image processing and started writing a script, ChangeImagecolor.py, to replace the main colors of images in batches.

Train of thought

1. PIP installs Pillow library to introduce Image class

2. Create a directory for storing converted images in the current directory

3. Obtain the current directory path and image files

4. Iterate over all Image files and create corresponding Image objects

5. Obtain the background color rGBA value of the Image object

6. Traverse all pixels of the Image object

7. Replace the pixel color that is not the background with the input color value to convert

8. Save the Image object to a new directory

Code implementation


from PIL import Image
import os

class ChangeImageColor(object):

    @classmethod
    def startHandle(self, rgb):
        Get the current path and create a new directory to output the result image
        path = os.getcwd() + '/images/res'
        npath = os.getcwd() + '/images/res/result/'
        if not os.path.exists(npath):
            os.makedirs(npath)
        else:
            Delete the following files if the same directory exists
            for root, dirs, files in os.walk(npath):
                for file_name in files:
                    os.remove(npath + file_name)
        
        # new color value
        nr,ng,nb = rgb
        # Store background color
        br,bg,bb, ba = 0.0.0.0
        Walk through the directory
        for root, dirs, files in os.walk(path):
            print('root: ', root)  The current directory path
            print('dirs: ', dirs)  All subdirectories under the current path
            print('files: ', files)  All non-directory subfiles in the current path
            
            Go through all the image files
            for file_name in files:
                iffile_name ! ='.DS_Store':
                    image = Image.open(root + '/' + file_name)
                    if image is not None:
                        image_width, image_height = image.size
                        Walk through Image for each pixel
                        for i in range(image_width):
                            for j in range(image_height):
                                xy = (i,j)
                                # Below is getting pixels and comparing pixels
                                color = image.getpixel(xy)
                                color_num = len(color)
                                Check whether the color has alpha
                                if color_num == 4:
                                    r, g, b, a = color
                                    if i == 0 and j == 0:
                                        br, bg, bb, ba = color
                                    ifbr ! = rorbg ! = gorbb ! = b:# Replace pixels and keep alpha
                                        image.putpixel(xy, (nr, ng, nb,a))

                                elif color_num == 3:
                                    r, g, b = color
                                    if i == 0 and j == 0:
                                        br, bg, bb = color
                                    ifbr ! = rorbg ! = gorbb ! = b: image.putpixel(xy, (nr, ng, nb)) image.save(npath + file_name)Convert hexadecimal to RGB
    @classmethod
    def hex2rgb(self, hexcolor):
        rgb = ((hexcolor >> 16) & 0xff,
               (hexcolor >> 8) & 0xff,
               hexcolor & 0xff
               )
        return rgb

if __name__ == '__main__':
    hexColor = int(input('Please enter new hexadecimal color value :'), 16)
    ChangeImageColor.startHandle(ChangeImageColor.hex2rgb(hexColor))
Copy the code

demo

The result directory is to convert the new image

Personal website: www.wuhaichao.com

Personal Open source project