压缩文件缩略图 python 实现

可以支持zip,rar,7zip,tar.gz等等各式

输入压缩文件名称,返回一个xml文件结构

#!usr/bin/python

#coding=utf-8
import uuid
import os
import zipfile
import re
import sys
import officetoimage
import rarfile
import tarfile
import subprocess


########SET CODE TO DEAL CHINESE############
default_encoding = 'utf-8'
if sys.getdefaultencoding()!=default_encoding:
    reload(sys)
    sys.setdefaultencoding(default_encoding)


#######TO GENERATE XML USING LIST##########
#######DIR IS LIST OF FILE STRUCT##########
def xml_generate(dir):
    body = ''
    for i in dir:
        if i.partition('/')[2] == '':            
            if(i.endswith('/')):
                body +="<directory name=\""+i.partition('/')[0] +'\">'
                tmp =[ j for j in dir if j.startswith(i) and j!=i]
                for j in range(len(tmp)):
                    tmp[j] = re.sub('^'+i,'',tmp[j])                                   
                if len(tmp)>0:
                    body += xml_generate(tmp)                   
                body +="</directory>"
            else:
                body +="<file>"+i.partition('/')[0]+"</file>"           
    return body


            
#######THIS IS A START TO GENERATE XML########## 
#######XML WILL BE WRITE TO FILE NAMED ZIP FILENAME##########
def xml_start(dir,outname):
    body = xml_generate(dir)            
    head = """<?xml version="1.0" encoding="UTF-8" ?>
<source>%s</source>""" %body
    tmp = outname.split('/')[0]
    if os.path.exists(tmp) is not True:
        os.makedirs(tmp,0755)
    out = open(outname,'w')
    out.write(head)
    out.close()
    
   
#######TO START DEAL ZIP##########        
def zip_deal(filename,readname,pwd):
    
    try:
        file_to_deal = zipfile.ZipFile(filename,'r')
    except IOError:
        print 'error zip'
        sys.exit(0)
   
    file_to_deal.setpassword(pwd)
    try:
        document=file_to_deal.read(readname)
    except:
        out = str(uuid.uuid1())
        command = '7z e -otmp/'+out+' -p'+pwd+' '+filename+ ' '+readname
        os.popen(command)    
        return 'tmp/'+out+'/'+readname.split('/')[-1]
        
    file_to_deal.close()
    
    return document


#######TO START DEAL RAR##########        
def rar_deal(filename,readname,pwd):
    try:
        file_to_deal = rarfile.RarFile(filename)
    except IOError:
        print 'error rar open'
        sys.exit(0)
        
    if file_to_deal.needs_password():
        file_to_deal.setpassword(pwd)
    try:
        document=file_to_deal.read(readname)
    except:
        print 'error rar read'
        sys.exit(0)
        
    file_to_deal.close()   
    return document


#######TO START DEAL TAR##########        
def tar_deal(filename,readname):
    try:
        file_to_deal = tarfile.open(filename)
    except IOError:
        print 'error'
        sys.exit(0)
   
    try:
        do = file_to_deal.extractfile(readname)
    except:
        print 'error'
        sys.exit(0)
    document = do.read()   
    file_to_deal.close()   
    return document


#######TO START DEAL ZIP##########        
def z7_deal(filename,readname,pwd):
    uuid_s = str(uuid.uuid1())
    command = '7z e -otmp/'+uuid_s+' -p'+pwd+' '+filename+ ' '+readname
    os.popen(command)    
    return 'tmp/'+uuid_s+'/'+readname.split('/')[-1]




#######FILE TO ZIP AND GET THE FILE STRUCT########## 
#######IF IS FILE RETURN PDF########## 
def file_to_zip(filename,pwd):
    out = 'tmp/' + str(uuid.uuid1())+'.xml'
    file_in = filename.partition('/')
    try:
        file_to_deal = zipfile.ZipFile(file_in[0],'r')
    except IOError:
        print 'error'
        sys.exit(0)
        
    search_list = file_to_deal.namelist()
    file_to_deal.close()
    if filename.endswith('.zip'):
        xml_start(search_list,out)  
        return out,'success'
    else :
        dir = 'tmp/'+str(uuid.uuid1())
        outname = dir+'/'+file_in[-1].split('/')[-1]   
        if os.path.exists(dir) is not True:
            os.makedirs(dir,0755)
        path= file_in[-1]
        file_content = zip_deal(file_in[0],path.decode('utf-8'),pwd)
        out = open(outname,'w')
       
        out.write(file_content)
        out.close()
        name_pdf = officetoimage.file_to_pdf(outname)
        return outname,name_pdf
    
def file_to_rar(filename,pwd):
    out = 'tmp/'+str(uuid.uuid1())+'.xml'
    file_in = filename.partition('/')
    try:
        file_to_deal = rarfile.RarFile(file_in[0],'r')
    except IOError:
        print 'error rar'
        sys.exit(0)     
    if file_to_deal.needs_password():
        file_to_deal.setpassword(pwd)
    search_list = file_to_deal.namelist()    
   
    for f in file_to_deal.infolist():
        if f.isdir():
            i = search_list.index(f.filename)
            search_list[i] += '/'
            
    file_to_deal.close()    
    for i in range(len(search_list)):
        search_list[i] = search_list[i].replace('\\','/')
        
    if filename.endswith('.rar'):
        xml_start(search_list,out)  
        return out,'success'
    else :
        dir = 'tmp/'+str(uuid.uuid1())
        outname = dir+'/'+file_in[-1].split('/')[-1]   
        if os.path.exists(dir) is not True:
            os.makedirs(dir,0755)
        #outname = 'tmp/'+str(uuid.uuid1())+'/'+file_in[-1].split('/')[-1]         
        path= file_in[-1]
        file_content = rar_deal(file_in[0],path.decode('utf-8'),pwd)
        out = open(outname,'w')
        out.write(file_content)
        out.close()
        name_pdf = officetoimage.file_to_pdf(outname)
        return outname,name_pdf
    
def file_to_tar(filename,pwd):
    out = 'tmp/'+str(uuid.uuid1())+'.xml'
    file_in = filename.partition('/')
    try:
        file_to_deal = tarfile.open(file_in[0],'r')
    except IOError:
        print 'error'
        sys.exit(0)     
    
    search_list = file_to_deal.getnames() 
    for f in search_list:
        if file_to_deal.getmember(f).isdir():
            i = search_list.index(f)
            search_list[i] += '/'  
            
    file_to_deal.close()    
        
    if filename.endswith('.tar') or filename.endswith('.tar.gz'):
        xml_start(search_list,out)  
        return out,'success'
    else :
        dir = 'tmp/'+str(uuid.uuid1())
        outname = dir+'/'+file_in[-1].split('/')[-1]   
        if os.path.exists(dir) is not True:
            os.makedirs(dir,0755)
        #outname = 'tmp/'+str(uuid.uuid1())+'/'+file_in[-1].split('/')[-1]        
        path= file_in[-1]
        file_content = tar_deal(file_in[0],path.decode('utf-8'))
        out = open(outname,'w')
        out.write(file_content)
        out.close()
        name_pdf = officetoimage.file_to_pdf(outname)
        return outname,name_pdf
    
def file_to_7z(filename,pwd):
    #out = 'tmp/' + filename.split('.')[0]+'.xml'
    out = 'tmp/'+str(uuid.uuid1())+'.xml'
    #print out
    file_in = filename.partition('/')
    if pwd == None:
        pwd =''
    if filename.endswith('.7z') :
        command = '7z l -p'+pwd+' '+filename 
        f = os.popen(command)    
        content = f.readlines()
        if content[6].startswith('Error'):
            return 'error 7z'
        for i in range(len(content)):
            if content[i].startswith('-----'):
                content = content[i+1:-2]
                break
       
        search_list = []
        for s in content:
            if s.split(' ')[2][0] == 'D':
                search_list.append(s.split(' ')[-1][:-1]+'/')
            else:
                search_list.append(s.split(' ')[-1][:-1])
         
        xml_start(search_list,out)  
        return out,'success'
    else :       
        path= file_in[-1]
        file_path = z7_deal(file_in[0],path.decode('utf-8'),pwd)
        name_pdf = officetoimage.file_to_pdf(file_path)
        return file_path,name_pdf
    


##### FILENAME IS FILE.ZIP OR FILE.ZIP/FILE#######    
if __name__ == '__main__':     
  
    filename = sys.argv[1]
    try:
        pwd = sys.argv[2]
    except:
        pwd = ''
    
    if filename.split('/')[0].endswith('.zip'):
        file_path,dir_content = file_to_zip(filename,pwd)
    elif filename.split('/')[0].endswith('.rar'):
        file_path,dir_content = file_to_rar(filename,pwd)
    elif filename.split('/')[0].endswith('.tar.gz') or filename.split('/')[0].endswith('.tar') :
        file_path,dir_content = file_to_tar(filename,pwd)
    elif filename.split('/')[0].endswith('.7z'):
        file_path,dir_content = file_to_7z(filename,pwd)
    else:
        dir_content = 'error code'
    print file_path,dir_content
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
bkViewer中文版是一款非常方便数码照片的浏览和集中处理工具,并且它还可以批量预览图片缩略图,如果您打算截图多个图片的预览效果,选它就对了。 软件说明 bkViewer不会在磁盘中增加任何冗余信息,直接利用现存文件夹方式对图片进行预览和浏览; bkViewer通过外挂程序对图片进行处理,同时也具有图片缩放、翻转、剪切、亮度锐度饱和度调整等最常用的基本编辑功能; bkViewer可以直接显示EXIF/IPTC/XMP/ICC数码照片拍摄参数信息和直方图,可详细查看镜头型号、防抖、快门次数等厂商标记; bkViewer支持解析的厂商标记包括Canon、Casio、Epson、FujiFilm、Kodak、KonicaMinolta、Leica、Nikon、Olympus、Panasonic、Pentax、Ricoh、Sanyo、Sigma、Sony等多家厂商; bkViewer支持通过IE、Firefox、Opera、Chrome右键菜单或扩展在线查看网页图片的拍摄信息; bkViewer支持实时像素拾色,方便的播放幻灯片或发送电子邮件,或将图片拖放到QQ窗口传递; bkViewer对后期处理的图片自动建立PS目录进行备份。当然,您也可以直接编辑而不备份,决定权在您; bkViewer支持图片预读以提升浏览速度,批量缩放等功能支持多核系统并行处理。它只有一个数百K的可执行文件,可以方便的拷贝运行; 除jpg、bmp、dib、rle、tif、png、gif、wmf等通用图片格式外,bkViewer还支持ttf、ttc字体预览,以及Canon(CR2/CRW), Nikon(NEF/NRW), Fuji(RAF), Leica(RAW/DNG), Kodak(DCR/KDC), Olympus(ORF), Pentax(DNG/PEF/RAW), Sony(ARW/SR2), Minolta(MRW), Panasonic(RAW/RW2), Richo(DNG), Samsung(SRW/DNG), Leaf(MOS), Hasselblad(3FR), Mamiya(MEF), Epson(ERF)等原始格式图片浏览及标记解析。 从bkViewer 3.0版本开始使用Windows GDI 图像处理引擎,未安装GDI 的系统需要下载GdiPlus.dll并放入bkViewer所在目录或系统目录。
Unifie(缩略图浏览)是一款缩略图查看软件,体积小巧,占用电脑资源少,但能提供给您最快的查看图片缩略图速度。 XP图像缩略图无法显示的解决方法: 可能是装了ACD的原因,文件夹的图片不能预览了,在网上看到一个解决的方法,很不错:) 症状:在XP或者其他操作系统里,在新装的系统里,图片文件在文件夹里显示缩略图的时候,你能看到图片的预览图像。但是由于一些原因出现后,这种预览图不再出现,给我们使用图像文件的时候带来了不少的麻烦。 原因:一般情况下,当我们安装了某些看图或者图像处理类软件(如ACDSee或者Photoshop)之后,这些软件会更改文件关联,让自己这成为开启某种图像文件格式的主程序。如果用户没用卸载程序而是强行删除这些软件,那么这些程序在Windows注册表中的文件关联还会保留,但由于该程序已被删除,所以Windows将无法打开原先可以支持的图片格式。 解决方法: 在“开始→运行”中输入“regsvr32 shimgvw.dll ”(启用图像预览); 然后运行“regsvr32 shmedia.dll” (启用影像预览)。 操作成功后会弹出窗口提示“……中的……成功”,按确定即可。 如果要取消预览,比如取消视频预览,运行“regsvr32 /u shmedia.dll”即可。 PS:我试过了,保证好用,有遇到此类问题的朋友不妨一试。 Unifie截图:

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值