python實現(xiàn)按長寬比縮放圖片
更新時間:2018年06月07日 11:19:10 作者:風(fēng)勻坊
這篇文章主要為大家詳細介紹了python實現(xiàn)按長寬比縮放圖片,具有一定的參考價值,感興趣的小伙伴們可以參考一下
使用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")
感言
有興趣的朋友可以將圖片路徑,長寬值,背景顏色等參數(shù)化
封裝成api做為個公共服務(wù)
本文源碼下載
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python開發(fā)企業(yè)微信機器人每天定時發(fā)消息實例
這篇文章主要介紹了Python開發(fā)企業(yè)微信機器人每天定時發(fā)消息實例,需要的朋友可以參考下2020-03-03
Python中sorted()函數(shù)的強大排序技術(shù)實例探索
排序在編程中是一個基本且重要的操作,而Python的sorted()函數(shù)則為我們提供了強大的排序能力,在本篇文章中,我們將深入研究不同排序算法、sorted()?函數(shù)的靈活性,以及各種排序場景下的最佳實踐2024-01-01
Python實現(xiàn)進度條和時間預(yù)估的示例代碼
這篇文章主要介紹了Python實現(xiàn)進度條和時間預(yù)估的代碼,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-06-06
Python3.5內(nèi)置模塊之time與datetime模塊用法實例分析
這篇文章主要介紹了Python3.5內(nèi)置模塊之time與datetime模塊用法,結(jié)合實例形式分析了Python3.5 time與datetime模塊日期時間相關(guān)操作技巧,需要的朋友可以參考下2019-04-04

