python批量修改圖片大小的方法
本文實(shí)例為大家分享了python批量修改圖片大小的具體代碼,供大家參考,具體內(nèi)容如下
引用的模塊
from PIL import Image
Image的使用
def resize_image(img_path):
try:
mPath, ext = os.path.splitext(img_path)
if astrcmp(ext, ".png") or astrcmp(ext, ".jpg"):
img = Image.open(img_path)
(width, height) = img.size
if width != new_width:
new_height = int(height * new_width / width)
out = img.resize((new_width, new_height), Image.ANTIALIAS)
new_file_name = '%s%s' % (mPath, ext)
out.save(new_file_name, quality=100)
Py_Log("圖片尺寸修改為:" + str(new_width))
else:
Py_Log("圖片尺寸正確,未修改")
else:
Py_Log("非圖片格式")
except Exception, e:
print e
def printFile(dirPath):
print "file: " + dirPath
resize_image(dirPath)
return True
引用
if __name__ == '__main__':
path = "E:\pp\icon_setting.png"
new_width = 50
try:
b = printFile(path)
Py_Log("\r\n **********\r\n" + "*********圖片處理完畢*********" + "\r\n **********\r\n")
except:
print "Unexpected error:", sys.exc_info()
上述是修改單一的圖片,若要批量修改文件夾下的所有圖片,則要使用循環(huán),在上面基礎(chǔ)添加 例如:
def BFS_Dir(dirPath, dirCallback=None, fileCallback=None):
queue = []
ret = []
queue.append(dirPath);
while len(queue) > 0:
tmp = queue.pop(0)
if os.path.isdir(tmp):
ret.append(tmp)
for item in os.listdir(tmp):
queue.append(os.path.join(tmp, item))
if dirCallback:
dirCallback(tmp)
elif os.path.isfile(tmp):
ret.append(tmp)
if fileCallback:
fileCallback(tmp)
return ret
第一個(gè)參數(shù)為圖片的目錄路徑,第二個(gè)參數(shù)是(目錄路勁的回掉方法),第三個(gè)參數(shù)是圖片處理回掉方法
源代碼參考:Python_Tool
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python實(shí)現(xiàn)數(shù)通設(shè)備tftp備份配置文件示例
這篇文章主要介紹了python實(shí)現(xiàn)數(shù)通設(shè)備tftp備份配置文件示例,需要的朋友可以參考下2014-04-04
python開發(fā)實(shí)例之Python的Twisted框架中Deferred對(duì)象的詳細(xì)用法與實(shí)例
這篇文章主要介紹了python開發(fā)實(shí)例之Python的Twisted框架中Deferred對(duì)象的詳細(xì)用法與實(shí)例,需要的朋友可以參考下2020-03-03
淺談PyTorch的可重復(fù)性問題(如何使實(shí)驗(yàn)結(jié)果可復(fù)現(xiàn))
今天小編就為大家分享一篇淺談PyTorch的可重復(fù)性問題(如何使實(shí)驗(yàn)結(jié)果可復(fù)現(xiàn)),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-02-02
Python將大量遙感數(shù)據(jù)的值縮放指定倍數(shù)的方法(推薦)
本文介紹基于Python中的gdal模塊,批量讀取大量多波段遙感影像文件,分別對(duì)各波段數(shù)據(jù)加以數(shù)值處理,并將所得處理后數(shù)據(jù)保存為新的遙感影像文件的方法,感興趣的朋友一起看看吧2025-01-01
Python報(bào)錯(cuò)TypeError: object of type ‘gener
在Python開發(fā)的復(fù)雜世界中,報(bào)錯(cuò)信息就像神秘的謎題,困擾著開發(fā)者和環(huán)境配置者,其中,TypeError: object of type ‘generator’ has no len()這個(gè)報(bào)錯(cuò),常常在不經(jīng)意間打亂我們的開發(fā)節(jié)奏,本文讓我們一起深入探究這個(gè)報(bào)錯(cuò)問題,為Python開發(fā)之路掃除障礙2024-10-10

