python缩小图片尺寸
时间: 2023-11-14 11:12:16 浏览: 211
使用Python的Pillow库可以轻松地缩小图片尺寸。下面是一个示例代码:
```
from PIL import Image
# 打开图片文件
im = Image.open("test.jpg")
# 设置新的图片尺寸
width = 500
height = 500
# 调整图片尺寸
im_resized = im.resize((width, height))
# 保存新的图片文件
im_resized.save("test_resized.jpg")
```
在这个示例代码中,我们首先使用`Image.open()`方法打开图片文件,然后使用`resize()`方法调整图片尺寸,最后使用`save()`方法保存新的图片文件。你可以根据实际情况修改变量`width`和`height`来设置新的图片尺寸。
相关问题
python 缩小图片尺寸
### 使用Python调整图像大小并缩小图片尺寸
#### 安装必要的库
为了能够操作图像,在Python中通常会使用`Pillow`库。可以通过pip命令安装此库:
```bash
pip install pillow
```
#### 加载图像文件
一旦安装完成,就可以通过导入`Image`模块来加载想要处理的图像文件。
```python
from PIL import Image
image_path = 'example.jpg' # 图像路径
img = Image.open(image_path)
```
#### 调整图像大小至指定宽度和高度
对于直接设置新的宽度(new_width)和高度(new_height),可以调用`resize()`方法[^1]。
```python
new_size = (800, 600) # 新的尺寸为800x600像素
resized_img = img.resize(new_size)
```
#### 维持原始比例缩放图像
如果希望在缩小的同时维持原有的宽高比,则可以在计算新尺寸时考虑这一点。这里给出一个函数用于按比例缩小图像[^3]。
```python
def resize_image_keep_ratio(img, base_width=None, base_height=None):
width_percent = (base_width / float(img.size[0])) if base_width else None
height_percent = (base_height / float(img.size[1])) if base_height else None
if not width_percent and height_percent:
size = int(img.size[0] * height_percent), base_height
elif width_percent and not height_percent:
size = base_width, int(img.size[1] * width_percent)
else:
raise ValueError('Please provide either a target width or height.')
return img.resize(size)
# 假设我们只想设定最大宽度而保持原有比例
max_width = 800
resized_with_ratio = resize_image_keep_ratio(img, base_width=max_width)
```
#### 保存修改后的图像
最后一步就是将经过调整的新图存储到磁盘上。
```python
output_path = 'resized_example.jpg'
resized_img.save(output_path)
print(f'Successfully saved resized image to {output_path}')
```
上述过程展示了如何利用Python中的Pillow库有效地调整图像大小以及按照一定规则缩小图片尺寸[^2]。
怎么使用Python代码缩小图片尺寸
你可以使用Python的Pillow库来缩小图片尺寸。具体的步骤如下:
1. 安装Pillow库:在命令行中输入`pip install Pillow`。
2. 导入Pillow库:在Python文件中导入Pillow库,代码如下:
```python
from PIL import Image
```
3. 打开图片:使用`Image.open()`方法打开需要缩小的图片,代码如下:
```python
image = Image.open('image.jpg')
```
4. 缩小图片:使用`Image.resize()`方法缩小图片,代码如下:
```python
width, height = image.size
new_width = int(width / 2)
new_height = int(height / 2)
new_image = image.resize((new_width, new_height))
```
上述代码将原始图片的宽度和高度分别除以2,然后使用`resize()`方法生成新的缩小后的图片。
5. 保存图片:使用`Image.save()`方法保存缩小后的图片,代码如下:
```python
new_image.save('new_image.jpg')
```
上述代码将缩小后的图片保存为`new_image.jpg`文件。
完整的代码如下:
```python
from PIL import Image
# 打开图片
image = Image.open('image.jpg')
# 缩小图片
width, height = image.size
new_width = int(width / 2)
new_height = int(height / 2)
new_image = image.resize((new_width, new_height))
# 保存图片
new_image.save('new_image.jpg')
```
阅读全文
相关推荐
















