获取图片宽高,若与指定宽高不同,改变图片大小为指定宽高并输出。使用python
时间: 2023-04-09 08:04:53 浏览: 117
你可以使用Python的Pillow库来获取图片的宽高并改变图片大小。以下是一个示例代码:
```python
from PIL import Image
def resize_image(input_path, output_path, width, height):
with Image.open(input_path) as image:
# 获取原始图片的宽高
original_width, original_height = image.size
# 如果原始图片的宽高与指定的宽高相同,则不需要改变图片大小
if original_width == width and original_height == height:
image.save(output_path)
return
# 计算缩放比例
scale = min(width / original_width, height / original_height)
# 计算新的宽高
new_width = int(original_width * scale)
new_height = int(original_height * scale)
# 缩放图片
resized_image = image.resize((new_width, new_height))
# 创建一个新的空白图片
output_image = Image.new('RGB', (width, height), (255, 255, 255))
# 将缩放后的图片粘贴到新的空白图片中心
x = (width - new_width) // 2
y = (height - new_height) // 2
output_image.paste(resized_image, (x, y))
# 保存图片
output_image.save(output_path)
# 使用示例
resize_image('input.jpg', 'output.jpg', 800, 600)
```
这个函数接受四个参数:输入图片路径、输出图片路径、指定宽度和指定高度。它会读取输入图片,计算缩放比例并缩放图片,然后将缩放后的图片粘贴到一个新的空白图片中心,并保存为输出图片。如果原始图片的宽高与指定的宽高相同,则不需要改变图片大小。
阅读全文
相关推荐















