溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

python批量圖片處理簡單示例

發布時間:2020-09-18 16:59:13 來源:腳本之家 閱讀:171 作者:沈偉-測試前行者 欄目:開發技術

本文實例講述了python批量圖片處理。分享給大家供大家參考,具體如下:

#!/usr/bin/python
#coding:utf-8
import os
from PIL import Image
#源目錄
MyPath = 'C:/Users/Eric/Desktop/python_text/20161214/test_Image/'
#輸出目錄
OutPath = 'C:/Users/Eric/Desktop/python_text/20161214/outpath/'
def processImage(filesoure, destsoure, name, imgtype):
  '''
  filesoure是存放待轉換圖片的目錄
  destsoure是存在輸出轉換后圖片的目錄
  name是文件名
  imgtype是文件類型
  '''
  imgtype = 'jpeg' if imgtype == '.jpg' else 'png'
  #打開圖片
  im = Image.open(filesoure + name)
  #縮放比例
  rate =max(im.size[0]/640.0 if im.size[0] > 60 else 0, im.size[1]/1136.0 if im.size[1] > 1136 else 0)
  if rate:
    im.thumbnail((im.size[0]/rate, im.size[1]/rate))
  im.save(destsoure + name, imgtype)
def run():
  #切換到源目錄,遍歷源目錄下所有圖片
  os.chdir(MyPath)
  for i in os.listdir(os.getcwd()):
    #檢查后綴
    postfix = os.path.splitext(i)[1]
    if postfix == '.jpg' or postfix == '.png':
      processImage(MyPath, OutPath, i, postfix)
if __name__ == '__main__':
  run()

更多關于Python相關內容可查看本站專題:《Python圖片操作技巧總結》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經典教程》

希望本文所述對大家Python程序設計有所幫助。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女