溫馨提示×

溫馨提示×

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

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

怎么在python中使用PIL合并多張圖片

發(fā)布時間:2021-03-25 16:42:55 來源:億速云 閱讀:571 作者:Leah 欄目:開發(fā)技術(shù)

怎么在python中使用PIL合并多張圖片?相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。

具體內(nèi)容如下

 
import os 
import Image 
 
def image_resize(img, size=(1500, 1100)): 
  """調(diào)整圖片大小 
  """ 
  try: 
    if img.mode not in ('L', 'RGB'): 
      img = img.convert('RGB') 
    img = img.resize(size) 
  except Exception, e: 
    pass 
  return img 
 
def image_merge(images, output_dir='output', output_name='merge.jpg', \ 
        restriction_max_width=None, restriction_max_height=None): 
  """垂直合并多張圖片 
  images - 要合并的圖片路徑列表 
  ouput_dir - 輸出路徑 
  output_name - 輸出文件名 
  restriction_max_width - 限制合并后的圖片最大寬度,如果超過將等比縮小 
  restriction_max_height - 限制合并后的圖片最大高度,如果超過將等比縮小 
  """ 
  max_width = 0 
  total_height = 0 
  # 計算合成后圖片的寬度(以最寬的為準)和高度 
  for img_path in images: 
    if os.path.exists(img_path): 
      img = Image.open(img_path) 
      width, height = img.size 
      if width > max_width: 
        max_width = width 
      total_height += height 
 
  # 產(chǎn)生一張空白圖 
  new_img = Image.new('RGB', (max_width, total_height), 255) 
  # 合并 
  x = y = 0 
  for img_path in images: 
    if os.path.exists(img_path): 
      img = Image.open(img_path) 
      width, height = img.size 
      new_img.paste(img, (x, y)) 
      y += height 
 
  if restriction_max_width and max_width >= restriction_max_width: 
    # 如果寬帶超過限制 
    # 等比例縮小 
    ratio = restriction_max_height / float(max_width) 
    max_width = restriction_max_width 
    total_height = int(total_height * ratio) 
    new_img = image_resize(new_img, size=(max_width, total_height)) 
 
  if restriction_max_height and total_height >= restriction_max_height: 
    # 如果高度超過限制 
    # 等比例縮小 
    ratio = restriction_max_height / float(total_height) 
    max_width = int(max_width * ratio) 
    total_height = restriction_max_height 
    new_img = image_resize(new_img, size=(max_width, total_height)) 
   
  if not os.path.exists(output_dir): 
    os.makedirs(output_dir) 
  save_path = '%s/%s' % (output_dir, output_name) 
  new_img.save(save_path) 
  return save_path 
   
if __name__ == '__main__': 
  image_merge(images=['900-000-000-0501a_b.jpg', '900-000-000-0501b_b.JPG', '1216005237382a_b.jpg'])

看完上述內(nèi)容,你們掌握怎么在python中使用PIL合并多張圖片的方法了嗎?如果還想學到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細節(jié)

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

AI