前言有一天我们在编辑后台操作的时候,说每次上传ppt,pdf,word,每个文件都要导出一次作为图片,然后一个上传(png作为预览,ppt,pdf,word源文件不能直接下载),说效率太低了。我问是否有办法只上传文件。当时想了想,每次上传都转一遍确实效率很低,因为有些导出的图片可能有几十张。最后通过GitHub和博主。最终解决了图像自动传输的问题。第一次写python脚本,报错,不优雅。欢迎指出~本文需要python3.9.5版本的windows平台,需要安装MicrosoftOffice。转到本地->传输图片->上传到云存储->获取远程图片连接->存储到数据库。连接数据库查询需要传输的集合defconnectDatabase():conn=pymysql.connect(host='127.0.0.1',user='root',password="",database='pic',port=3306)#host=localhost#也可以这样写,如果127.0.0.1不可用#登录数据库cur=conn.cursor(pymysql.cursors.DictCursor)return{"conn":conn,"cur":cur}#获取需要传输的文件集defgetUrlArr(cur):sql='select*frompic'#编写自己的sql语句arr=''try:cur.execute(sql)ex=cur.execute(sql)arr=cur.fetchmany(ex)exceptExceptionase:raiseefinally:returnarr下载文件到本地#下载文件到本地defdownLoad(url):print('----url-----',url)文件名=''尝试:后缀=os.path.basename(url).split('.')[1]filename="miaohui."+suffixifos.path.exists(filename):#如果文件存在,删除文件os.remove(filename)wget.download(url,filename)除了IOError:print('Downloadfailed',url)else:print('\n')print('Downloadsucceeded',url)returnfilenameppttopicture#pipinstallpywin32#初始化PPTdefinit_powerpoint():powerpoint=win32com.client.Dispatch('PowerPoint.Application')#comtypes.client.CreateObject("Powerpoint.Application")powerpoint.Visible=1returnpowerpoint#PPTtopngdefppt2png(url,pptFileName,powerpoint):try:ppt_path=os.path.abspath(pptFileName)ppt=powerpoint.Presentations.Open(ppt_path)#另存为图片img_path=os.path.abspath(downLoad_path+'.png')ppt.SaveAs(img_path,18)#17另存为jpg格式#关闭打开的ppt文件ppt.Close()exceptIOError:print('PPTtopngfailed',url)else:print("PPTtopngfailed",url)topdf图片#pipinstallPyMuPDF#pdftoimagedefpdf2png(_url,pptFileName):imagePath=os.path.abspath(downLoad_path)try:pdfDoc=fitz.open(pptFileName)forpginrange(pdfDoc.pageCount):page=pdfDoc[pg]rotate=int(0)#每个维度的缩放因子为1.3,这将为我们生成分辨率增加2.6的图像#如果这里没有设置,默认图片尺寸为:792X612,dpi=96zoom_x=1.33333333#(1.33333333-->1056x816)(2-->1584x1224)zoom_y=1.33333333mat=fitz.Matrix(zoom_x,zoom_y).prerotate(rotate)pix=page.get_pixmap(matrix=mat,alpha=False)ifnotos.path.exists(imagePath):#判断存放图片的文件夹是否存在os.makedirs(imagePath)#如果图片文件夹不存在如果存在则创建pix.save(imagePath+'/'+'slideshow%s.png'%pg)#将图片写入指定文件夹exceptIOError:print('Failedtoconvertpdftopng',_url)else:print("pdf转png成功",_url)word转图片word转图片需要转一次,先转word转pdf,再转pdf转图片。#WordtoPdfdefword2pdf(word_file):'''Convertwordfiletopdffile:paramword_file:wordfile:return:'''#获取word格式处理对象word=Dispatch('Word.Application')#使用Doc对象打开文件doc_=word.Documents.Open(word_file)#另存为pdf文件suffix=os.path.basename(word_file).split('.')[1]doc_.SaveAs(word_file.replace(suffix,"pdf"),FileFormat=17)print(word_file,'----转换成pdf成功')#关闭doc对象doc_.Close()#退出word对象word.Quit()returnos.path.basename(word_file).split('.')[0]+'.pdf'然后调用上面的pdf2png上传到对象存储这里就不贴了。我们使用华为云OBS。阿里云、腾讯云等对象存储都有自己的Python版SDK,接入也很方便。最后组合在一起调用if__name__=='__main__':connect=connectDatabase()powerpoint=init_powerpoint()downArr=getUrlArr(connect['cur'])foriindownArr:if(os.path.exists('./'+downLoad_path)):removeFileInFirstDir('./'+downLoad_path)_url=unquote(i['url'])id=i['id']pptFileName=downLoad(_url)#downloadfileif(('.pdf'在_url)==True):pdf2png(_url,pptFileName)elif(('.doc'in_url)==True):_file=os.path.abspath(pptFileName)pdfNmae=word2pdf(_file)pdf2png(_url,pdfNmae)else:ppt2png(_url,pptFileName,powerpoint)#transfertopngimgArr=uploadImg(_url)#上传图片到云存储并获取远程链接setData(_url,id,imgArr,connect)#savetodatabasetime.sleep(2)print('\n')print('\n')connect['cur'].close()#关闭游标connect['conn'].close()#断开数据库并释放资源powerpoint.Quit()input("Enteranykeytoend")因为是内部使用,所以可以使用pyinstaller打包成exe提供给操作方面,数据上传运行后,可以自动批量传输图片#pytoexepyinstaller-c-F-ia.icoppt_to_img.py最后,希望这篇文章能帮到你。有问题欢迎指正~换工作?寻找面试问题?来前端面试题库wx搜索进阶大前端
