国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python實現按長寬比縮放圖片

2020-02-15 21:42:07
字體:
來源:轉載
供稿:網友

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

代碼

# -*- coding: utf-8 -*-from PIL import Imageclass 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做為個公共服務

本文源碼下載

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 吉林市| 永胜县| 涞源县| 西峡县| 绥阳县| 荥阳市| 南漳县| 钟山县| 鸡西市| 北票市| 小金县| 泾川县| 渭源县| 阿巴嘎旗| 泸水县| 辽宁省| 宝清县| 安顺市| 周口市| 镇远县| 鄢陵县| 邵阳县| 蕲春县| 翼城县| 南岸区| 乐清市| 长武县| 慈溪市| 定安县| 紫阳县| 克山县| 乌什县| 佛坪县| 固镇县| 新乐市| 天祝| 西峡县| 宣武区| 湖南省| 嘉定区| 武定县|