用Python Pillow 改变图像的宽度和高度的比例

用Python Pillow 改变图像的宽度和高度的比例

Python Imaging Library(PIL的扩展)是Python语言中事实上的图像处理包。它集成了轻量级的图像处理工具,有助于编辑、创建和保存图像。这个模块没有预装在Python中。所以要安装它,请在命令行中执行以下命令。

pip install pillow

为了改变高度和宽度的比例,我们将从它们中增加或减少任何随机值。

用到的方法

  • Image.open(fp, mode=’r’)方法。该方法用于打开图像。
  • Image.resize(size, resample=0)方法。该方法用于调整图像的大小。 在调整大小的过程中会发生插值,由于插值的原因,无论图像是被上调(调整到比原来高的尺寸)还是下调(调整到比原来低的尺寸),图像的质量都会发生变化。

步骤:

  • 我们将首先拍摄一张图片。
  • 然后我们将找到它的高度和宽度。
  • 然后,我们将在其中添加和减去任何随机数字以改变比例。
  • 然后,我们将保存图像。

示例:

使用的图片:

用Python改变图像的宽度和高度的比例--Pillow

# Python program to change the ratio of height and
# width of an image 
from PIL import Image
  
# Taking image as input
img = Image.open('logo.png')
  
# Getting height and width of the image
height = img.size[0]
width = img.size[1]
  
# Printing ratio before conversion
print('Ratio before conversion:', width/height)
  
# Changing the height and width of the image
width = width + 25
height = height - 25
  
# Resizing the image
img = img.resize((width ,height), Image.ANTIALIAS)
  
# Printing the ratio after conversion
print('Ratio after conversion:', width/height)
  
# Saving the resized image
img.save('Resized Image.png')

输出:

Ratio before conversion: 1.0
Ratio after conversion: 1.25

输出 图片:

用Python改变图像的宽度和高度的比例--Pillow

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

Python pil