python實(shí)現(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做為個(gè)公共服務(wù)
本文源碼下載
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python開發(fā)企業(yè)微信機(jī)器人每天定時(shí)發(fā)消息實(shí)例
這篇文章主要介紹了Python開發(fā)企業(yè)微信機(jī)器人每天定時(shí)發(fā)消息實(shí)例,需要的朋友可以參考下2020-03-03
Python爬蟲實(shí)戰(zhàn)項(xiàng)目掌握酷狗音樂的加密過程
在常見的幾個(gè)音樂網(wǎng)站里,酷狗可以說是最好爬取的啦,什么彎都沒有,所以最適合小白入門爬蟲,本篇針對(duì)爬蟲零基礎(chǔ)的小白,所以每一步驟我都截圖并詳細(xì)解釋了,其實(shí)我自己看著都啰嗦,歸根到底就是兩個(gè)步驟的請(qǐng)求,還請(qǐng)大佬繞路勿噴2021-09-09
Python中sorted()函數(shù)的強(qiáng)大排序技術(shù)實(shí)例探索
排序在編程中是一個(gè)基本且重要的操作,而Python的sorted()函數(shù)則為我們提供了強(qiáng)大的排序能力,在本篇文章中,我們將深入研究不同排序算法、sorted()?函數(shù)的靈活性,以及各種排序場景下的最佳實(shí)踐2024-01-01
Python實(shí)現(xiàn)進(jìn)度條和時(shí)間預(yù)估的示例代碼
這篇文章主要介紹了Python實(shí)現(xiàn)進(jìn)度條和時(shí)間預(yù)估的代碼,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-06-06
python學(xué)習(xí)入門細(xì)節(jié)知識(shí)點(diǎn)
我們整理了關(guān)于python入門學(xué)習(xí)的一些細(xì)節(jié)知識(shí)點(diǎn),對(duì)于學(xué)習(xí)python的初學(xué)者很有用,一起學(xué)習(xí)下。2018-03-03
Python3.5內(nèi)置模塊之time與datetime模塊用法實(shí)例分析
這篇文章主要介紹了Python3.5內(nèi)置模塊之time與datetime模塊用法,結(jié)合實(shí)例形式分析了Python3.5 time與datetime模塊日期時(shí)間相關(guān)操作技巧,需要的朋友可以參考下2019-04-04

