国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

利用python編寫一個圖片主色轉換的腳本

2020-02-16 10:57:12
字體:
來源:轉載
供稿:網友

前言

最近由于項目特需老是替換主題顏色,同時app里一些資源icon圖片主色也要改,美工不提供切圖只能靠自己了,開始想在iconfont上面找但是數量比較多太浪費時間,然后就想到python的Pillow在圖像處理方便很強大。

Pillow是Python里的圖像處理庫(PIL:Python Image Library),提供了了廣泛的文件格式支持,強大的圖像處理能力,主要包括圖像儲存、圖像顯示、格式轉換以及基本的圖像處理操作等。

本文就編寫了一個批量替換圖片主色的腳本changeImageColor.py。

實現思路

      1.pip 安裝Pillow庫引入Image類

      2.在當前目錄下創建存放轉換后圖片目錄

      3.獲取當前目錄路徑,以及圖片文件

      4.遍歷所有圖片文件并創建對應Image對象

      5.獲取Image對象背景顏色rgba值

      6.遍歷Image對象所有像素點

      7.把不是背景像素點顏色替換為要轉換輸入顏色值

      8.保存Image對象到新目錄下面

代碼實現

from PIL import Imageimport osclass ChangeImageColor(object):  @classmethod  def startHandle(self, rgb):    # 獲取當前路徑,并創建新目錄用于輸出結果image    path = os.getcwd() + '/images/res'    npath = os.getcwd() + '/images/res/result/'    if not os.path.exists(npath):      os.makedirs(npath)    else:      # 如果存在相同新目錄那么刪除下面文件      for root, dirs, files in os.walk(npath):        for file_name in files:          os.remove(npath + file_name)        # 新顏色值    nr,ng,nb = rgb    # 存放背景顏色    br,bg,bb, ba = 0, 0, 0, 0    # 遍歷目錄    for root, dirs, files in os.walk(path):      print('root: ', root) # 當前目錄路徑      print('dirs: ', dirs) # 當前路徑下所有子目錄      print('files: ', files) # 當前路徑下所有非目錄子文件            # 遍歷下所有圖片文件      for file_name in files:        if file_name != '.DS_Store':          image = Image.open(root + '/' + file_name)          if image is not None:            image_width, image_height = image.size            # 遍歷Image每個像素            for i in range(image_width):              for j in range(image_height):                xy = (i,j)                # 下面是獲取像素和比較像素                color = image.getpixel(xy)                color_num = len(color)                # 判斷顏色是否有alpha值                if color_num == 4:                  r, g, b, a = color                  if i == 0 and j == 0:                    br, bg, bb, ba = color                  if br != r or bg != g or bb != b:                    # 替換像素并保留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                  if br != r or bg != g or bb != b:                    image.putpixel(xy, (nr, ng, nb))            image.save(npath + file_name)  # 把16進制轉換為rgb  @classmethod  def hex2rgb(self, hexcolor):    rgb = ((hexcolor >> 16) & 0xff,        (hexcolor >> 8) & 0xff,        hexcolor & 0xff        )    return rgbif __name__ == '__main__':  hexColor = int(input('請輸入新16進制顏色值:'), 16)  ChangeImageColor.startHandle(ChangeImageColor.hex2rgb(hexColor))            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 通州市| 南通市| 扶风县| 西乌珠穆沁旗| 呼伦贝尔市| 灌阳县| 红原县| 莱西市| 鹿邑县| 西乌珠穆沁旗| 塘沽区| 双鸭山市| 宜昌市| 蓝山县| 鄂托克前旗| 余干县| 潍坊市| 郧西县| 连城县| 东丽区| 卫辉市| 新乐市| 日照市| 翼城县| 鄢陵县| 资中县| 贵南县| 龙口市| 和林格尔县| 黄梅县| 日喀则市| 扎兰屯市| 永新县| 彰武县| 双柏县| 丰城市| 宜宾县| 青岛市| 上饶市| 汝南县| 西平县|