溫馨提示×

溫馨提示×

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

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

使用python怎么批量修改圖片大小

發(fā)布時間:2021-05-19 17:28:35 來源:億速云 閱讀:447 作者:Leah 欄目:開發(fā)技術

今天就跟大家聊聊有關使用python怎么批量修改圖片大小,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。

引用的模塊

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),在上面基礎添加 例如:

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

python主要應用領域有哪些

1、云計算,典型應用OpenStack。2、WEB前端開發(fā),眾多大型網站均為Python開發(fā)。3.人工智能應用,基于大數據分析和深度學習而發(fā)展出來的人工智能本質上已經無法離開python。4、系統(tǒng)運維工程項目,自動化運維的標配就是python+Django/flask。5、金融理財分析,量化交易,金融分析。6、大數據分析。

看完上述內容,你們對使用python怎么批量修改圖片大小有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問一下細節(jié)

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

AI