欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python實現按長寬比縮放圖片

 更新時間:2018年06月07日 11:19:10   作者:風勻坊  
這篇文章主要為大家詳細介紹了python實現按長寬比縮放圖片,具有一定的參考價值,感興趣的小伙伴們可以參考一下

使用python按圖片固定長寬比縮放圖片到指定圖片大小,空白部分填充為黑色。

代碼

# -*- coding: utf-8 -*-

from PIL import Image

class image_aspect():

 def __init__(self, image_file, aspect_width, aspect_height):
  self.img = Image.open(image_file)
  self.aspect_width = aspect_width
  self.aspect_height = aspect_height
  self.result_image = None

 def change_aspect_rate(self):
  img_width = self.img.size[0]
  img_height = self.img.size[1]

  if (img_width / img_height) > (self.aspect_width / self.aspect_height):
   rate = self.aspect_width / img_width
  else:
   rate = self.aspect_height / img_height

  rate = round(rate, 1)
  print(rate)
  self.img = self.img.resize((int(img_width * rate), int(img_height * rate)))
  return self

 def past_background(self):
  self.result_image = Image.new("RGB", [self.aspect_width, self.aspect_height], (0, 0, 0, 255))
  self.result_image.paste(self.img, (int((self.aspect_width - self.img.size[0]) / 2), int((self.aspect_height - self.img.size[1]) / 2)))
  return self

 def save_result(self, file_name):
  self.result_image.save(file_name)


if __name__ == "__main__":
 image_aspect("./source/test.jpg", 1920, 1080).change_aspect_rate().past_background().save_result("./target/test.jpg")

感言

有興趣的朋友可以將圖片路徑,長寬值,背景顏色等參數化
封裝成api做為個公共服務

本文源碼下載

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

最新評論