python實(shí)現(xiàn)按長(zhǎng)寬比縮放圖片
使用python按圖片固定長(zhǎng)寬比縮放圖片到指定圖片大小,空白部分填充為黑色。
代碼
# -*- 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")
感言
有興趣的朋友可以將圖片路徑,長(zhǎng)寬值,背景顏色等參數(shù)化
封裝成api做為個(gè)公共服務(wù)
本文源碼下載
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python編程matplotlib繪圖挑鉆石seaborn小提琴和箱線圖
這篇文章主要為大家介紹了Python編程如何使用matplotlib繪圖來(lái)挑出完美的鉆石以及seaborn小提琴和箱線圖,有需要的朋友可以借鑒參考下,希望能夠優(yōu)速幫助2021-10-10Python3 實(shí)現(xiàn)隨機(jī)生成一組不重復(fù)數(shù)并按行寫入文件
下面小編就為大家分享一篇Python3 實(shí)現(xiàn)隨機(jī)生成一組不重復(fù)數(shù)并按行寫入文件的示例。具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-04-04Python設(shè)置Socket代理及實(shí)現(xiàn)遠(yuǎn)程攝像頭控制的例子
這篇文章主要介紹了Python設(shè)置Socket代理及實(shí)現(xiàn)遠(yuǎn)程攝像頭控制的例子,皆是對(duì)socket模塊的實(shí)際運(yùn)用,需要的朋友可以參考下2015-11-11淺談PyTorch中in-place operation的含義
這篇文章主要介紹了淺談PyTorch中in-place operation的含義,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-06-06python GUI庫(kù)圖形界面開(kāi)發(fā)之PyQt5線程類QThread詳細(xì)使用方法
這篇文章主要介紹了python GUI庫(kù)圖形界面開(kāi)發(fā)之PyQt5線程QThread類詳細(xì)使用方法,需要的朋友可以參考下2020-02-02