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做為個公共服務
本文源碼下載
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Python編程matplotlib繪圖挑鉆石seaborn小提琴和箱線圖
這篇文章主要為大家介紹了Python編程如何使用matplotlib繪圖來挑出完美的鉆石以及seaborn小提琴和箱線圖,有需要的朋友可以借鑒參考下,希望能夠優(yōu)速幫助2021-10-10淺談PyTorch中in-place operation的含義
這篇文章主要介紹了淺談PyTorch中in-place operation的含義,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06python GUI庫圖形界面開發(fā)之PyQt5線程類QThread詳細使用方法
這篇文章主要介紹了python GUI庫圖形界面開發(fā)之PyQt5線程QThread類詳細使用方法,需要的朋友可以參考下2020-02-02