国产探花免费观看_亚洲丰满少妇自慰呻吟_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做為個公共服務

本文源碼下載

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 五指山市| 安宁市| 新昌县| 秦安县| 辽阳县| 衡阳市| 荣成市| 南召县| 固安县| 上林县| 晋中市| 遂溪县| 台中县| 慈溪市| 南郑县| 苏尼特左旗| 茶陵县| 随州市| 扬中市| 衡南县| 宁河县| 巴林左旗| 滁州市| 封丘县| 建始县| 五台县| 江永县| 澜沧| 诸暨市| 淮滨县| 海南省| 盱眙县| 荔浦县| 昂仁县| 重庆市| 名山县| 鹿邑县| 阿荣旗| 翼城县| 迭部县| 石城县|