首页 > 技术文章 > 图片base64文件编码 文件路径 获取图片的尺寸大小和统计文件的大小取平均值

xiaoxiao-niao 2018-03-02 17:06 原文

#coding:utf-8
import base64
import os
from PIL import Image
import re

def Filepath():
    '''路径'''
    cur_path1 = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
    return cur_path1

def ImagName():
    '''遍历目录下jpg的文件'''
    if not  os.path.exists(os.path.join(Filepath(),"conf")):
        os.mkdir(os.path.join(Filepath(),"conf"))
        return " folder location path : %s "%os.path.join(Filepath(),"conf")
    else:
        filepath =os.walk(os.path.join(Filepath(),"conf"))
        jpglist = []
        for path,d,filelists in filepath:
            for filename in filelists:
                if filename.endswith("jpg"):
                    jpglist.append(os.path.join(path,filename))
        return jpglist

def convert_image():
    '''将文件转换成base64编码'''
    # Picture ==> base64 encode
    with open(ImagName(), 'rb') as fin:
        image_data = fin.read()
        base64_data = base64.b64encode(image_data)
        return base64_data

if __name__ == '__main__':
   from time import sleep
   count = []
   if ImagName() == "folder location path":
       print "folder location path :" + os.path.join(Filepath(),"conf")
   else:
       for i in ImagName():
           img = Image.open(i)
           image_size = os.path.getsize(i)
           count.append(image_size)
           print str(re.findall(r"\d.+?\.jpg",i)[0]) +":" + str(img.size) + "," + "filesize" + ":" + str(str(image_size/1024) + "k")
       if count == []:
          print "not jpc picture"
       else:
          print "average : " + str(sum(count)/1024/len(count)) + "k"
   sleep(10)

 

推荐阅读