python批量修改图片大小
时间: 2023-04-05 18:03:39 浏览: 83
可以使用Pillow库来批量修改图片大小,具体操作可以参考以下代码:
```python
from PIL import Image
import os
# 设置图片路径和目标大小
path = 'image_folder/'
target_size = (500, 500)
# 遍历文件夹中的所有图片
for filename in os.listdir(path):
if filename.endswith('.jpg') or filename.endswith('.png'):
# 打开图片并修改大小
img = Image.open(os.path.join(path, filename))
img = img.resize(target_size)
# 保存修改后的图片
new_filename = os.path.splitext(filename)[0] + '_resized' + os.path.splitext(filename)[1]
img.save(os.path.join(path, new_filename))
```
这段代码会将`image_folder`文件夹中所有的`.jpg`和`.png`图片修改为大小为`(500, 500)`的图片,并在原文件名后加上`_resized`后缀保存。
相关问题
用Python批量修改图片大小的代码
可以使用Python的PIL库来实现批量修改图片大小,示例代码如下: from PIL import Image # 加载图片
image = Image.open('filename') #修改图片大小
image = image.resize((300, 300)) # 保存图片
image.save('filename')
python 批量修改 jpg图片大小
以下是Python批量修改jpg图片大小的代码示例:
```python
from PIL import Image
import os
def resize_image(img_path, output_path, size):
with Image.open(img_path) as img:
img.thumbnail(size)
img.save(output_path)
def batch_resize_images(input_dir, output_dir, size):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for filename in os.listdir(input_dir):
if filename.endswith('.jpg'):
img_path = os.path.join(input_dir, filename)
output_path = os.path.join(output_dir, filename)
resize_image(img_path, output_path, size)
# 示例:将文件夹1中的所有jpg图片缩小为原来的一半并保存到文件夹2中
input_dir = '文件夹1'
output_dir = '文件夹2'
size = (2048, 2048)
batch_resize_images(input_dir, output_dir, size)
```
上述代码使用了Pillow库中的Image模块来处理图片,通过`thumbnail()`方法将图片缩小到指定大小,并使用`save()`方法保存到指定路径。`batch_resize_images()`函数则是遍历指定文件夹中的所有jpg图片,并调用`resize_image()`函数进行批量处理。