python实现按长宽比缩放图片

yipeiwu_com5年前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设计】。

相关文章

python实现AES加密与解密

AES加密方式有五种:ECB, CBC, CTR, CFB, OFB 从安全性角度推荐CBC加密方法,本文介绍了CBC,ECB两种加密方法的python实现 python 在 Windo...

利用python如何处理nc数据详解

前言 这两天帮一个朋友处理了些 nc 数据,本以为很简单的事情,没想到里面涉及到了很多的细节和坑,无论是“知难行易”还是“知易行难”都不能充分的说明问题,还是“知行合一”来的更靠谱些,...

Python数据类型之列表和元组的方法实例详解

Python数据类型之列表和元组的方法实例详解

引言 我们前面的文章介绍了数字和字符串,比如我计算今天一天的开销花了多少钱我可以用数字来表示,如果是整形用 int ,如果是小数用 float ,如果你想记录某件东西花了多少钱,应该使用...

基于pandas数据样本行列选取的方法

注:以下代码是基于python3.5.0编写的 import pandas food_info = pandas.read_csv("food_info.csv") # ------...

Pyqt实现无边框窗口拖动以及窗口大小改变

本文实例为大家分享了Pyqt实现无边框窗口拖动及大小改变的具体代码,供大家参考,具体内容如下 做个记录,绘制边框阴影可以忽略这里不是主要 根据网上某位仁兄Qt的实现转过来的大笑,上完整代...