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

相关文章

Apache,wsgi,django 程序部署配置方法详解

Apache,wsgi,django 程序部署配置方法详解

本文实例讲述了Apache,wsgi,django 程序部署配置方法。分享给大家供大家参考,具体如下: 前面写过一篇文章,ngixn,uwsgi,django,python 环境配置,有...

python cv2读取rtsp实时码流按时生成连续视频文件方式

python cv2读取rtsp实时码流按时生成连续视频文件方式

我就废话不多说了,直接上代码吧! # coding: utf-8 import datetime import cv2 import os ip = '192.168.3.160...

python中pandas.DataFrame对行与列求和及添加新行与列示例

本文介绍的是python中pandas.DataFrame对行与列求和及添加新行与列的相关资料,下面话不多说,来看看详细的介绍吧。 方法如下: 导入模块: from pandas i...

PyQt5笔记之弹出窗口大全

PyQt5笔记之弹出窗口大全

本文实现了PyQt5个各种弹出窗口:输入框、消息框、文件对话框、颜色对话框、字体对话框、自定义对话框 其中,为了实现自定义对话框的返回值,使用了信号/槽 本文基于 windows 7 +...

简单介绍Python中的readline()方法的使用

 readline()方法从文件中读取一整行。尾部的换行符保持在字符串中。如果大小参数且非负,那么一个最大字节数,包括结尾的换行和不完整的行可能会返回。 遇到EOF时立即返回一...