python把文件夹下图片重新设置尺寸
时间: 2023-06-16 16:08:31 浏览: 31
你可以使用Python的Pillow库来重新设置文件夹下图片的尺寸。以下是一个示例代码,其中将文件夹下的所有图片调整为宽度为300像素,高度按比例缩放:
```python
from PIL import Image
import os
# 定义文件夹路径和目标宽度
folder_path = 'your_folder_path'
target_width = 300
# 遍历文件夹
for filename in os.listdir(folder_path):
# 判断文件是否为图片
if filename.endswith('.jpg') or filename.endswith('.png'):
# 打开图片
img_path = os.path.join(folder_path, filename)
img = Image.open(img_path)
# 计算目标高度并重新设置尺寸
w, h = img.size
target_height = int(h * target_width / w)
img = img.resize((target_width, target_height))
# 保存图片
img.save(img_path)
```
请确保已安装Pillow库,可以使用以下命令安装:
```
pip install Pillow
```
相关问题
python把文件夹下的子文件里的图片重新设置尺寸
可以使用Pillow库来处理图片,并且使用os库来遍历文件夹和子文件夹中的图片文件。以下是一个示例代码,可以将文件夹下所有子文件夹中的图片文件缩放到指定尺寸:
```python
from PIL import Image
import os
# 设置目标尺寸
width, height = 500, 500
# 遍历文件夹和子文件夹中的所有图片文件
for root, dirs, files in os.walk("path/to/folder"):
for file in files:
# 判断文件扩展名是否为图片格式
if file.endswith(".jpg") or file.endswith(".jpeg") or file.endswith(".png") or file.endswith(".bmp"):
# 打开图片文件
image = Image.open(os.path.join(root, file))
# 缩放图片
image = image.resize((width, height))
# 保存缩放后的图片
image.save(os.path.join(root, file))
```
将 `path/to/folder` 替换为你实际的文件夹路径,运行代码即可将该文件夹下所有子文件夹中的图片文件缩放到指定尺寸。注意,该代码只处理常见的图片格式,如果需要处理其他格式的图片文件,可以在判断文件扩展名的部分加入对应的判断条件。
python读取文件夹下所有图片
你可以使用 Python 的 os 和 PIL 库来读取文件夹下所有图片。下面是一个示例代码:
```python
import os
from PIL import Image
folder_path = 'path/to/folder' # 文件夹路径
for filename in os.listdir(folder_path):
full_path = os.path.join(folder_path, filename)
if os.path.isfile(full_path):
try:
img = Image.open(full_path)
# 在这里进行你的操作,比如打印图片尺寸
print(filename, img.size)
except OSError:
print(f"{filename} is not an image.")
```
这段代码会遍历指定文件夹下的所有文件,如果是图片则使用 PIL 库打开并进行操作(这里仅示范了打印图片尺寸),如果不是图片则跳过。你可以根据实际需求修改代码。
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![exe](https://img-home.csdnimg.cn/images/20210720083343.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)