python 怎么改变图的大小
时间: 2024-02-11 10:09:28 浏览: 13
你可以使用Pillow(PIL)库中的Image类来改变图像的大小。以下是一个示例代码,其中将图像大小调整为宽度为300像素,高度按比例缩放:
```python
from PIL import Image
# 打开图像文件
image = Image.open("example.jpg")
# 调整大小并保持宽高比例
width, height = image.size
new_width = 300
new_height = int(height * new_width / width)
resized_image = image.resize((new_width, new_height))
# 保存调整大小后的图像
resized_image.save("example_resized.jpg")
```
在上面的代码中,我们首先打开图像文件,然后计算调整大小后的宽度和高度,保持宽高比例不变,并使用`resize`方法将图像调整为新的大小。最后,我们将调整大小后的图像保存到另一个文件中。
相关问题
python改变图像大小
可以使用PIL库中的resize()函数来改变图像大小。以下是一个示例代码:
```python
from PIL import Image
# 打开图像文件
image = Image.open('example.jpg')
# 定义新的宽度和高度
new_width = 600
new_height = 400
# 使用resize()函数改变图像大小
resized_image = image.resize((new_width, new_height))
# 保存新的图像文件
resized_image.save('resized_example.jpg')
```
在这个示例中,我们打开了一个名为“example.jpg”的图像文件,并定义了新的宽度和高度。然后,我们使用resize()函数改变图像大小,并将其保存为新的图像文件“resized_example.jpg”。
python改变显示图片的大小
使用PIL库可以轻松改变图片大小。以下是一个示例代码:
```python
from PIL import Image
# 打开图片
image = Image.open('example.jpg')
# 改变大小为宽度为200,高度按比例缩放
new_size = (200, int(image.size[1]/(image.size[0]/200)))
image = image.resize(new_size)
# 保存修改后的图片
image.save('example_resized.jpg')
```
在上述代码中,我们首先打开需要修改大小的图片,然后使用`resize()`方法将图片大小改变为指定的宽度和高度。最后,我们保存修改后的图片。