前言
本文的文字及圖片來源于網路,僅供學習、交流使用,不具有任何商業用途,著作權歸原作者所有,如有問題請及時聯系我們以作處理,
WHJWNAVY | 作者
Demo大師 | 來源
python 趣味實用小工具
概述
用python實作的三個趣味實用小工具: 圖片轉Execl工具 , 圖片轉TXT工具
準備作業
系統需求
所有的代碼都是基于 python3 的, 所以需要事先安裝好 python3 ,并設定好環境.
安裝方法詳見:
廖雪峰Python3教程-安裝Python3
官方安裝教程-英文
安裝必備庫
注意: 安裝程序中建議以管理員權限運行執行以下命令.
- 安裝PIL圖片處理庫pip install pillow
- 安裝qrcode二維碼處理工具pip install qrcode
- 安裝openpyxl Execl表格處理工具pip install openpyxl右鍵選單添加”復制檔案路徑”功能Win7系統如果使用的是Win7系統, 可以把以下代碼保存為 復制檔案路徑.reg 檔案, 雙擊運行添加注冊表, 就可以實作一鍵復制檔案路徑功能.
復制檔案路徑.reg
Windows Registry Editor Version 5.00
;檔案
[HKEY_CLASSES_ROOT\*\shell\copypath]
@="復制檔案路徑"
[HKEY_CLASSES_ROOT\*\shell\copypath\command]
;@="mshta vbscript:clipboarddata.setdata(\"text\",\"%1\")(close)"
;帶引號
;@="cmd.exe /c echo \"%1\"|clip"
;不帶引號
@="cmd.exe /c echo %1|clip"
;檔案夾
[HKEY_CLASSES_ROOT\Directory\shell\copypath]
@="復制檔案夾路徑"
[HKEY_CLASSES_ROOT\Directory\shell\copypath\command]
;@="mshta vbscript:clipboarddata.setdata(\"text\",\"%1\")(close)"
;帶引號
;@="cmd.exe /c echo \"%1\"|clip"
;不帶引號
@="cmd.exe /c echo %1|clip"
使用方法: 在任意檔案或檔案夾上單擊滑鼠右鍵選擇 復制檔案路徑 ,就可以很方便的把檔案或檔案夾的路徑復制到剪切板中. 如下圖:
Win10系統
Win10系統自帶了 復制路徑功能 .
使用方法: 先按住 Shift 鍵, 然后在任意檔案或檔案夾上單擊滑鼠右鍵選擇 復制路徑 ,就可以很方便的把檔案或檔案夾的路徑復制到剪切板中. 不過Win10自帶的 復制路徑 功能復制的結果包含引號,需要自己根據需要手動洗掉.
圖片轉Execl工具
概述
這是一個用于把圖片轉換成Execl表格的Python小工具, 用到了pillow、openpyxl、等第三方庫,
原理是打開一幅圖片, 先對圖片進行格式轉換個縮放, 然后依次讀取圖片每個像素的RGB值, 然后把該值作為Excel表格中對應單元格的背景色.最后再把每個單元格設定為高度與寬度相等的小正方形. 詳見代碼注釋.
源代碼
py_img_to_excel.py
from openpyxl.workbook import Workbook#匯入Workbook庫用與操作Execl作業簿
from openpyxl.styles import PatternFill, Color#匯入PatternFill,Color庫用與操作Execl單元格
from PIL import Image#匯入Image庫用與操作圖片檔案
import datetime
#把一個整數值轉換成26進制字串
#因為execl單元格的行坐標是26進制的, 比如"A", "Z", "AA", "AZ"
def dec_to_base26(d):
s = ""
m = 0
while d > 0:
m = d % 26
if m == 0:
m = 26
s = "{0:c}{1:s}".format(m+64, s)
d = (d - m) // 26
return s
#把一個26進制字串轉換成整數值
def base26_to_dec(s):
d = 0
j = 1
st = s.upper()
for x in range(0, len(st))[::-1]:
c = ord(st[x])
if c < 65 and c > 90:
return 0
d += (c - 64) * j
j *= 26
return d
#把一個整數坐標轉換成Execl坐標
#Execl坐標的行坐標是26進制的, 列坐標是10進制的,比如(AA, 100)
def decxy_to_excelxy(x, y):
return("{0:s}{1:d}".format(dec_to_base26(x), y))
#把像素點的rgb值轉換成Execl支持的十六進制字串, 形如 "AARRGGBB",
#其中AA表示透明度,這里設定為0, 比如 "00FF55FF"
def pixel_to_xrgbstr(pix):
return ("00{0:02X}{1:02X}{2:02X}".format(pix[0], pix[1], pix[2]))
#圖片轉Execl函式, imgName 表示帶全路徑的圖片名
def image_to_excel(imgName):
#創建一個 excel 作業簿
wb = Workbook()
ws = wb.active
#打開圖片檔案檔案
print("Open Image File [{0}]".format(imgName))
try:
img = Image.open(imgName)
except:
print("Error to Open [{0}]!!!".format(imgName))
#判斷圖片檔案的格式, 這里必須為"RGB"格式, 如果不是"RGB"格式,
#則用convert函式轉換成"RGB"格式.
if "RGB" == img.mode:
print("Size{0},Format({1}),Color({2})".format(img.size, img.format, img.mode))
else:
print("Not a RGB image file!!!")
img = img.convert("RGB")
print("Convert to RGB Success!!!")
#獲取圖片檔案寬和高
width = img.size[0]#寬度
height = img.size[1]#高度
zoom = 0
#如果圖片檔案大于 400*400像素,則對圖片進行縮放,縮放比例依照寬度和高度中的最大值
if width >= height:
maxsize = width
else:
maxsize = height
if maxsize >= 400:
zoom = maxsize / 400
width = int(width / zoom)
height = int(height / zoom)
img = img.resize((width, height))
print("Image Size too large, Resize to", img.size)
index = 0
print("Start Process!")
for w in range(width):#遍歷圖片的寬度,[0, width)
#顯示處理進度
index += 1
print("#", end="")
if index >= 60:#大于60換行
index = 0
print("")
for h in range(height):#遍歷圖片的高度[0, height)
pixel = img.getpixel((w, h))#獲取圖片當前坐標點的像素值
loc = decxy_to_excelxy(w+1, h+1)#把整數坐標轉換成Execl坐標(字串)
#print("LOC", loc)
c = ws[loc]#選中當前圖片像素點坐標對應的Execl單元格
col = pixel_to_xrgbstr(pixel)#把當前圖片像素點的顏色轉換成Execl單元格的顏色(字串)
#print("COL", col)
#用當前圖片像素點的顏色填充單元格底色
cfill = PatternFill(fill_type="solid", start_color=col)
c.fill = cfill
#把單元格的寬設定為1,高設定為6, 這樣單元格看上去就是一個(小)正方形
ws.column_dimensions[dec_to_base26(w+1)].width = 1
ws.row_dimensions[h+1].height = 6
print("\nProcess Done!")
#獲取當前時間,轉換成字串
timenow = datetime.datetime.now()
timestr = timenow.strftime("%Y-%m-%d-%H-%M-%S")
#生成的Execl檔案名用<原圖片檔案名+ 當前時間字串+ "..xlsx"后綴>作為檔案名
namestr = "{0}-{1}.xlsx".format(imgName, timestr)
print("Save File As [{0}]".format(namestr))
#保存新生成的Execl檔案
wb.save(namestr)
print("Save Done!")
name = input("Please Input Image File Name:")
print("Start......")
try:
image_to_excel(name)
except:
print("Error!!!!!!")
print("Over......")
為了方便使用這個工具, 而不需要每次都打開cmd手動執行 python py_img_to_excel.py命令, 可以新建一個 Img2Excel.bat 腳本檔案, 腳本內容如下. 把這個腳本檔案和 py_img_to_excel.py 檔案放在同一檔案夾下, 然后把該腳本檔案發送到桌面快捷方式, 以后直接雙擊這個腳本檔案就可以直接運行 py_img_to_excel.py 了
Img2Excel.bat
@echo off
set cur_path="%cd%\py_img_to_excel.py"
python %cur_path%
pause
運行方法
直接雙擊桌面 Img2Excel.bat 快捷方式就可以運行本工具, 然后程式等待用戶輸入一個帶全路徑的圖片檔案名, 這里可以使用剛才的 復制檔案路徑 工具直接復制圖片路徑粘貼過來即可.
圖片轉TxT工具
概述
這是一個用于把圖片轉換成TXT檔案的Python小工具, 用到了pillow等第三方庫.
原理是打開一幅圖片, 先對圖片進行格式轉換個縮放, 然后對影像二值化, 轉換成純黑白的影像, 接著依次讀取圖片每個像素的值寫入到文本檔案中, 如果該值不為0則寫入 @ ,否則寫入 空格 , 詳見代碼注釋.
源代碼
py_img_to_txt.py
from PIL import Image#匯入Image庫用與操作圖片檔案
import datetime
def image_to_txt(imgName):
#獲取當前時間,轉換成字串
timenow = datetime.datetime.now()
timestr = timenow.strftime("%Y-%m-%d-%H-%M-%S")
#生成的Txt檔案用<原圖片檔案名+ 當前時間字串+ ".txt"后綴>作為檔案名
namestr = "{0}-{1}.txt".format(imgName, timestr)
#打開或創建一個TxT檔案檔案
txt = open(namestr, "w+")
#打開圖片檔案檔案
print("Open Image File [{0}]".format(imgName))
try:
img = Image.open(imgName)
except:
print("Error to Open [{0}]!!!".format(imgName))
#判斷圖片檔案的格式, 這里必須為"RGB"格式, 如果不是"RGB"格式,
#則用convert函式轉換成"RGB"格式.
if "RGB" == img.mode:
print("Size{0},Format({1}),Color({2})".format(img.size, img.format, img.mode))
else:
print("Not a RGB image file!!!")
img = img.convert("RGB")
print("Convert to RGB Success!!!")
#獲取圖片檔案寬和高
width = img.size[0]
height = img.size[1]
zoom = 0
#如果圖片檔案大于 400*400像素,則對圖片進行縮放,縮放比例依照寬度和高度中的最大值
if width >= height:
maxsize = width
else:
maxsize = height
if maxsize >= 400:
zoom = maxsize / 400
width = int(width / zoom)
height = int(height / zoom)
img = img.resize((width, height))
print("Image Size too large, Resize to", img.size)
#把圖片檔案轉換成純黑白的圖片
img = img.convert("1")
index = 0
print("Start Process!")
for w in range(width):#遍歷圖片的寬度,[0, width)
#顯示處理進度
index += 1
print("#", end="")
txt.write("/*")
if index >= 60:#大于60換行
index = 0
print("")
for h in range(height):#遍歷圖片的高度[0, height)
pixel = img.getpixel((w, h))#獲取圖片當前坐標點的像素值
#print("w=", w, "h=", h, "pixel=", pixel)
if pixel != 0:#因為是純黑白影像,所以像素顏色只有0或255兩種值
txt.write("_")#非0則往txt中寫入"_"表示白色
#print("w=", w, "h=", h, "pixel=", pixel)
else:
txt.write("@")#0則往txt中寫入"@"表示黑色
#print("w=", w, "h=", h, "pixel=", pixel)
txt.write("*/")
txt.write("\n")
#保存新生成的TXT檔案
print("\nProcess Done!")
print("Save File As [{0}]".format(namestr))
txt.close()
print("Save Done!")
name = input("Please Input Image File Name:")
print("Start......")
try:
image_to_txt(name)
except:
print("Error!!!!!!")
print("Over......")
為了方便使用這個工具, 而不需要每次都打開cmd手動執行 python py_img_to_txt.py命令, 可以新建一個 Img2Txt.bat 腳本檔案, 腳本內容如下. 把這個腳本檔案和 py_img_to_txt.py 檔案放在同一檔案夾下, 然后把該腳本檔案發送到桌面快捷方式, 以后直接雙節這個腳本檔案就可以直接運行了py_img_to_txt.py 了
Img2Txt.bat
@echo off
set cur_path="%cd%\py_img_to_txt.py"
python %cur_path%
pause
運行方法
直接雙擊桌面 Img2Txt.bat 快捷方式就可以運行本工具, 然后程式等待用戶輸入一個帶全路徑的圖片檔案名, 這里可以使用剛才的 復制檔案路徑 工具直接復制圖片路徑粘貼過來即可.
PS:如有需要Python學習資料的小伙伴可以加下方的群去找免費管理員領取
可以免費領取原始碼、專案實戰視頻、PDF檔案等
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/3679.html
標籤:Python
