本文实例讲述了Python实现批量修改图片格式和大小的方法。分享给大家供大家参考,具体如
本文实例讲述了Python实现批量修改图片格式和大小的方法。分享给大家供大家参考,具体如下:
第一种方法用到opencv库
import os
import time
import cv2
def alter(path,object):
result = []
s = os.listdir(path)
count = 1
for i in s:
document = os.path.join(path,i)
img = cv2.imread(document)
img = cv2.resize(img, (20,20))
listStr = [str(int(time.time())), str(count)]
fileName = ''.join(listStr)
cv2.imwrite(object+os.sep+'%s.jpg' % fileName, img)
count = count + 1
alter('C:\\imgDemo','C:\\imgDemo1')
第二种方法用到PIL库
import os
import time
from PIL import Image
def alter(path,object):
s = os.listdir(path)
count = 1
for i in s:
document = os.path.join(path,i)
img = Image.open(document)
out = img.resize((20,20))
listStr = [str(int(time.time())), str(count)]
fileName = ''.join(listStr)
out.save(object+os.sep+'%s.jpg' % fileName)
count = count + 1
alter('C:\\imgDemo','C:\\imgDemo1')
运行上述代码可得到C:\imgDemo目录下对应批量生成的20*20大小的图片。
运行效果如下:
Python 批量修改 图片格式 大小 opencv库 PIL库