# -*- coding: utf-8 -*-
from PIL import Image
import openpyxl
import openpyxl.styles
from openpyxl.styles import PatternFill
from openpyxl.utils import get_column_letter
from progressbar import *
def RGB_to_Hex(rgb):
"""
RGB顏色轉換成16進制顏色
:param rgb:
:return:
"""
RGB = rgb.split(',') # 將RGB格式劃分開來
color = ''
for i in RGB:
num = int(i)
# 將R、G、B分別轉化為16進制拼接轉換并大寫 hex() 函數用于將10進制整數轉換成16進制,以字符串形式表示
color += str(hex(num))[-2:].replace('x', '0').upper()
return color
def img2excel(img_path,excelout_path):
"""
圖片轉換成excel
:param img_path: 圖片地址
:param excelout_path: excel保存地址
:return:
"""
img_src = Image.open(img_path)
#寬高
img_width=img_src.size[0]
img_height=img_src.size[1]
print("圖片寬%s,高%s"%(img_width,img_height))
# 類型
# print(img_src.mode)
if img_src.mode != "RGB":
img_src = img_src.convert('RGB')
str_strlist = img_src.load()
wb=openpyxl.Workbook()
wb.save(excelout_path)
wb=openpyxl.load_workbook(excelout_path)
sheet=wb["Sheet"]
sheet.title="img2excel"
cell_width = 1.0
cell_height = cell_width * (2.2862 / 0.3612)
print("正在瘋狂生成excel,請耐心等待...")
#進度條
widgets=['進度:',Percentage(),'',Bar('#'),'',Timer(),' ', ETA(), ' ']
pb=ProgressBar(widgets=widgets)
for w in pb(range(img_width)):
for h in range(img_height):
data = str_strlist[w,h]
# 把元組rgb顏色變成字符串,轉換成16進制顏色(1,2,3)-->'1,2,3'
color=str(data).replace("(","").replace(")","")
#16進制的顏色,不帶前面#號的,要#自己拼接到color前面即可
color=RGB_to_Hex(color)
# 設置填充顏色為color,solid參數表示填充實色
fille=PatternFill("solid",fgColor=color)
sheet.cell(h+1,w+1).fill=fille
print("生成完成,正在設置單元格格式...")
for i in range(1, sheet.max_row+1):
sheet.row_dimensions[i].height=cell_height
for i in range(1, sheet.max_column+1):
sheet.column_dimensions[get_column_letter(i)].width = cell_width
print('格式設置完成,正在保存excel...')
wb.save(excelout_path)
img_src.close()
print("保存excel成功!請打開[%s]查看"%excelout_path)
if __name__=='__main__':
import sys,os
if len(sys.argv)!=3:
print("請輸入圖片地址和excel保存的地址\n"
"例如命令行輸入 python img2excel_user.py D:/result.png D:/outExcel.xlsx")
sys.exit(0)
else:
img_virify=['.jpg','.png','.gif','.bmp','.jpeg','.jpe','.jfif']
excel_virify=['.xlsx','.xlsm','.xltx','.xltm']
# 圖片地址
img_path=sys.argv[1]
# excel保存地址
excelout_path=sys.argv[2]
endName=os.path.splitext(img_path)
if endName[1] not in img_virify:
print("請選擇支持的圖片類型",img_virify)
sys.exit(0)
endName_excel=os.path.splitext(excelout_path)
if endName_excel[1] not in excel_virify:
print("excel 格式不支持,請選擇支持的格式",excel_virify)
sys.exit(0)
img2excel(r""+img_path+"",excelout_path)
到此這篇關于python讀取圖片顏色值并生成excel像素畫的文章就介紹到這了,更多相關python讀取圖片顏色值生成excel像素畫內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!