Python工具 — 读取文件夹中所有图片+缩放并打包

import glob
from PIL import Image
import os
import zipfile
 
#获取image文件夹下的图片路径
path="image\\"
 
#获取到当前文件的目录,并检查是否有result文件夹,如果没有则创建
#image、result文件夹及该python文件路径均为:D:\PythonSpace\
Newimg_Path=os.getcwd()[:0]+'result\\'
if not os.path.exists(Newimg_Path):
        os.makedirs(Newimg_Path)
 
 
def changesize(img):
    img_name=img
    #打开图片
    oldimg=Image.open(path+img_name)
    #大小缩放为64*64
    new_img=oldimg.resize((64,64))
    #以原名称存储图片
    new_img.save(Newimg_Path+img_name)
 
#压缩文件        
def zipImagefile():
    #新建压缩包hahaha.zip,若压缩包已经存在,讲其覆盖
    azip=zipfile.ZipFile('hahaha.zip','w',zipfile.ZIP_DEFLATED)
    #os.walk()递归查找文件夹中的所有内容
    for current_path, subfolders, filesname in os.walk(r'D:\PythonSpace\result'):
        #filesname是一个列表,我们需要里面的每个文件名和当前路径组合
        for file in filesname:
            # 将当前路径与当前路径下的文件名组合,就是当前文件的绝对路径
            azip.write(os.path.join(current_path,file))
    #关闭资源
    azip.close()       
    
#读取图片及名称
for img in os.listdir(path):
    #不同格式
    if (img.endswith('.gif') or img.endswith('.png') or img.endswith('.jpg')):
        #修改图片,存储图片
        changesize(img) 
#压缩文件
zipImagefile()

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
读取文件夹中的所有图片文件,你可以使用Python的`os`和`PIL`库。下面是一个示例代码,演示了如何读取文件夹中的所有图片文件: ```python import os from PIL import Image def read_images_from_folder(folder_path): image_files = [] for filename in os.listdir(folder_path): if filename.endswith(".jpg") or filename.endswith(".png"): image_files.append(os.path.join(folder_path, filename)) images = [] for file_path in image_files: image = Image.open(file_path) images.append(image) return images # 指定文件夹路径 folder_path = "path/to/folder" # 调用函数读取图片 images = read_images_from_folder(folder_path) # 对读取到的图片进行操作 for image in images: # Do something with the image image.show() ``` 在上面的示例中,`read_images_from_folder()` 函数接受文件夹路径作为参数,并返回一个包含所有图片的 `Image` 对象列表。函数首先遍历文件夹中的所有文件,筛选出以 `.jpg` 或 `.png` 结尾的文件路径,并将其存储在 `image_files` 列表中。然后,函数遍历 `image_files` 列表,使用 `Image.open()` 打开每个图片文件,并将其添加到 `images` 列表中。最后,函数返回 `images` 列表。 你可以将 `folder_path` 更改为你想要读取图片的文件夹路径,并使用 `read_images_from_folder()` 函数读取该文件夹中的所有图片文件。然后,你可以对读取到的图片进行进一步的操作,比如显示、处理等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值