在Python中,调整图像大小可以通过多个库实现,以下是几个常用的库及其用法:
使用`resize-right-sdk`库
1. 安装库:
pip install resize-right-sdk
2. 导入库并初始化:
from resizeright import Resizeright
resizer = Resizeright(api_key='你的API密钥')
3. 调整图片大小并保存:
response = resizer.resize(
image_url='图片URL或本地路径',
width=100,
height=100,
resize_strategy='crop'
)
with open('output.jpg', 'wb') as f:
f.write(response.content)
使用`python-resize-image`库
1. 安装库:
pip install python-resize-image
2. 导入库并调整图片大小:
from PIL import Image
from resizeimage import resizeimage
with open('example.jpg', 'rb') as f:
with Image.open(f) as image:
resized_image = resizeimage.resize_cover(image, [200, 200])
resized_image.save('resized_example.jpg', image.format)
使用`Pillow`库
1. 安装库:
pip install Pillow
2. 导入库并加载图像:
from PIL import Image
image = Image.open('path_to_your_image.jpg')
3. 使用`resize`方法调整图像大小:
resized_image = image.resize((400, 300))
使用`OpenCV`库(`cv2`)
1. 导入库并读取图像:
import cv2
image = cv2.imread('image.jpg')
2. 设置目标大小并调用`resize`函数:
new_width = 500
new_height = 300
resized_image = cv2.resize(image, (new_width, new_height))
使用`numpy`调整数组大小
注意:`numpy.resize`用于调整NumPy数组的大小,不适用于图像处理。