python2.7开发photoshop一些经验
原因:由于项目汇交的时候许多的成果需要转为pdf、tiff等,而且有严格的分辨率、压缩格式的要求,还要保证清晰度,因此许多的转换软件无法做到photoshop的效果,故而采用photoshop自动化输出。之前利用javascript开发photoshop,效果还不错,但是不能有创建文件夹,node.js也没能在photoshp中利用起来,折腾很久,最终放弃。
开发环境:python2.7 + comtypes+photoshop2020+ PyCharm 注意:comtypes包安装及代码中使用到的包正确安装;photoshop也要正确安装。
例子:
import os
import sys
import shutil
import xlrd as xd
from ctypes import windll
import gc
reload(sys)
sys.setdefaultencoding('utf8')
from comtypes.client import CreateObject
class NJHelper:
def __init__(self):
self.jpgToTiff = CreateObject("Photoshop.Application")
def jpg_to_tiff(self, folder):
pdfCreate = None
try:
listAllFile = []
for root, dirs, files in os.walk(folder, topdown=False):
for name in files:
if name.endswith(".jpg"):
print(os.path.join(root, name))
listAllFile.append(os.path.join(root, name))
for pptfile in listAllFile:
pdfPath = os.path.splitext(pptfile)[0]
if pdfPath[-3:] != 'tiff':
pdfPath = pdfPath + ".tiff"
tiffSaveOptions = CreateObject("Photoshop.TiffSaveOptions")
tiffSaveOptions.embedColorProfile = True
tiffSaveOptions.alphaChannels = True
tiffSaveOptions.layers = True
tiffSaveOptions.imageCompression = 2
tiffSaveOptions.layerCompression = 1
pdfCreate = self.jpgToTiff.Open(pptfile)
pdfCreate.SaveAs(pdfPath, tiffSaveOptions)
pdfCreate.Close()
print ("seccess")
except:
print ("error")
pdfCreate.Close()
def jpgtotiff(self, listAllFile, savepath):
pdfCreate = None
try:
flg = 0
for pptfile in listAllFile:
flg += 1
pdfPath = savepath + "_" + str(flg).zfill(2) + ".tiff"
tiffSaveOptions = CreateObject("Photoshop.TiffSaveOptions")
tiffSaveOptions.embedColorProfile = True
tiffSaveOptions.alphaChannels = True
tiffSaveOptions.layers = True
tiffSaveOptions.imageCompression = 2
tiffSaveOptions.layerCompression = 1
pdfCreate = self.jpgToTiff.Open(pptfile)
pdfCreate.SaveAs(pdfPath, tiffSaveOptions)
pdfCreate.Close()
seccess = u"jpg转tiff:" + pdfPath + u"成功!"
print (seccess)
except:
err = u"jpg转tiff:" + pdfPath + u"失败!"
print (err)
pdfCreate.Close()
def addAllTiff(self, listAllFile, SavePath):
newDoc = None
try:
maxWidth = 0
totalHeight = 0
for pptfile in listAllFile:
doc = self.jpgToTiff.Open(pptfile)
totalHeight += doc.height
if doc.width > maxWidth:
maxWidth = doc.width
doc.close()
newDoc = self.jpgToTiff.documents.add(maxWidth, totalHeight, 300, "mytiff")
nextTop = 0
for pptfile in listAllFile:
doc1 = self.jpgToTiff.Open(pptfile)
doc1.activeLayer.copy()
self.jpgToTiff.activeDocument = newDoc
self.jpgToTiff.activeDocument.paste()
bounds = self.jpgToTiff.activeDocument.activeLayer.bounds
if (nextTop == 0):
self.jpgToTiff.activeDocument.activeLayer.translate(0, 0 - bounds[1])
else:
self.jpgToTiff.activeDocument.activeLayer.translate(0, nextTop - bounds[1])
nextTop += bounds[3] - bounds[1]
doc1.close()
if windll.user32.OpenClipboard(None):
windll.user32.EmptyClipboard()
windll.user32.CloseClipboard()
gc.collect()
tiffSaveoptions = CreateObject("Photoshop.TiffSaveOptions")
tiffSaveoptions.embedColorProfile = True
tiffSaveoptions.alphaChannels = True
tiffSaveoptions.layers = True
tiffSaveoptions.imageCompression = 2
tiffSaveoptions.layerCompression = 1
newDoc.SaveAs(SavePath, tiffSaveoptions)
seccess = u"合并" + SavePath + u"成功!"
print (seccess)
newDoc.Close()
del listAllFile
gc.collect()
except:
err = u"合并" + SavePath + u"出错,原因内存不足,请手动合并!"
print (err)
newDoc.Close()
gc.collect()
def addAllTiff1(self, folderPath, SavePath):
newDoc = None
try:
maxWidth = 0
totalHeight = 0
listAllFile = []
for root, dirs, files in os.walk(folderPath, topdown=False):
for name in files:
if name.endswith(".tif"):
print(os.path.join(root, name))
listAllFile.append(os.path.join(root, name))
for pptfile in listAllFile:
doc = self.jpgToTiff.Open(pptfile)
totalHeight += doc.height
if doc.width > maxWidth:
maxWidth = doc.width
doc.close()
newDoc = self.jpgToTiff.documents.add(maxWidth, totalHeight, 72, "mytiff")
nextTop = 0
for pptfile in listAllFile:
doc1 = self.jpgToTiff.Open(pptfile)
doc1.activeLayer.copy()
self.jpgToTiff.activeDocument = newDoc
self.jpgToTiff.activeDocument.paste()
bounds = self.jpgToTiff.activeDocument.activeLayer.bounds
if (nextTop == 0):
self.jpgToTiff.activeDocument.activeLayer.translate(0, 0 - bounds[1])
else:
self.jpgToTiff.activeDocument.activeLayer.translate(0, nextTop - bounds[1])
nextTop += bounds[3] - bounds[1]
doc1.close()
if windll.user32.OpenClipboard(None):
windll.user32.EmptyClipboard()
windll.user32.CloseClipboard()
gc.collect()
tiffSaveoptions = CreateObject("Photoshop.TiffSaveOptions")
tiffSaveoptions.embedColorProfile = True
tiffSaveoptions.alphaChannels = True
tiffSaveoptions.layers = True
tiffSaveoptions.imageCompression = 2
tiffSaveoptions.layerCompression = 1
newDoc.SaveAs(SavePath, tiffSaveoptions)
seccess = u"合并" + SavePath + u"成功!"
print (seccess)
newDoc.Close()
del listAllFile
gc.collect()
except:
err = u"合并" + SavePath + u"出错,原因内存不足,请手动合并!"
print (err)
newDoc.Close()
gc.collect()
def getJHByCbfbm(self, listd, cbfbm):
for i in listd:
filtered = i[0]
jh = filtered
if (i[0] == cbfbm):
jh = i[1]
return jh
def getFilterFile(self, folder, find_file):
allFile = []
for parents, adds, filenames in os.walk(folder):
for filename in filenames:
if find_file in filename:
allFile.append(parents + "\\" + filename)
return allFile
def nj(self, xiangzpath, savePath, xlspath, xq):
data = xd.open_workbook(xlspath)
sheet = data.sheet_by_name('Sheet1')
listd = []
for r in range(sheet.nrows):
data1 = []
for c in range(sheet.ncols):
data1.append(sheet.cell_value(r, c))
listd.append(list(data1))
try:
for dircun in os.listdir(xiangzpath):
cun = os.path.join(xiangzpath, dircun)
print(cun)
for dirxz in os.listdir(cun):
xz = os.path.join(xiangzpath, dircun, dirxz)
print(xz)
for dirxz_cg_dyb in os.listdir(xz):
cg = os.path.join(xz, dirxz_cg_dyb)
print(cg)
if (cg.endswith("登记颁证成果")):
print("djdc")
for root_cbf, dirs_cbf, files_cbf in os.walk(cg + "\\承包方调查表", topdown=True):
for name in files_cbf:
print (os.path.join(root_cbf, name))
cbfbm = root_cbf[-18:]
allFiles = []
fm = []
fm = self.getFilterFile(cg + "\\确权登记颁证材料封面\\" + cbfbm, ".jpg")
ml = []
ml = self.getFilterFile(cg + "\\确权登记颁证材料目录\\" + cbfbm, ".jpg")
qslyzmcl = []
qslyzmcl = self.getFilterFile(cg + "\\权属来源证明材料\\" + cbfbm, ".jpg")
cbfdb = []
cbfdb.append(os.path.join(root_cbf, name))
cbfdbsms = []
cbfdbsms = self.getFilterFile(cg + "\\承包方代表声明书\\" + cbfbm, ".jpg")
zjtzscg = []
zjtzscg = self.getFilterFile(cg + "\\指界通知书(存根)\\" + cbfbm, ".jpg")
dkdcb = []
dkdcb = self.getFilterFile(cg + "\\地块调查表\\" + cbfbm, ".jpg")
ghb = []
ghb = self.getFilterFile(cg + "\\归户表\\" + cbfbm, ".jpg")
gswyy = []
gswyy = self.getFilterFile(cg + "\\公示无异议书\\" + cbfbm, ".jpg")
cbht = []
cbht = self.getFilterFile(cg + "\\承包合同\\" + cbfbm, ".jpg")
cbfdjsqs = []
cbfdjsqs = self.getFilterFile(cg + "\\承包方登记颁证申请书\\" + cbfbm, ".jpg")
djb = []
djb = self.getFilterFile(cg + "\\登记簿\\" + cbfbm, ".jpg")
dksyt = []
dksyt = self.getFilterFile(cg + "\\地块示意图\\" + cbfbm, ".jpg")
listpath = cg.split("\\")
jh = self.getJHByCbfbm(listd, cbfbm)
if jh.strip():
lsjh = jh.split("-")
pdfname = "0" + lsjh[0] + "-2019-永久-确权登记类-" + lsjh[1]
newpath = os.path.join(savePath, listpath[1], listpath[2], listpath[3],
xq + "农经权档案数字化加工单页TIFF", "0" + lsjh[0], "2019", "永久",
"确权登记类",
lsjh[1])
alltiffnewpath = os.path.join(savePath, listpath[1], listpath[2], listpath[3],
xq + "农经权档案数字化加工多页TIFF", "0" + lsjh[0], "2019",
"永久",
"确权登记类", lsjh[1])
newfile_path = os.path.join(newpath, pdfname)
if (os.path.exists(newpath) == False):
os.makedirs(newpath)
if (os.path.exists(alltiffnewpath) == False):
os.makedirs(alltiffnewpath)
if len(fm) > 0 and len(ml) > 0 and len(qslyzmcl) > 0 and len(cbfdb) > 0 and len(
cbfdbsms) > 0 and len(zjtzscg) > 0 and len(dkdcb) > 0 and len(
ghb) > 0 and len(
gswyy) > 0 and len(cbht) > 0 and len(cbfdjsqs) > 0 and len(djb) > 0 and len(
dksyt) > 0:
allFiles.extend(fm)
allFiles.extend(ml)
allFiles.extend(qslyzmcl)
allFiles.extend(cbfdb)
allFiles.extend(cbfdbsms)
allFiles.extend(zjtzscg)
allFiles.extend(dkdcb)
allFiles.extend(ghb)
allFiles.extend(gswyy)
allFiles.extend(cbht)
allFiles.extend(cbfdjsqs)
allFiles.extend(djb)
allFiles.extend(dksyt)
self.jpgtotiff(allFiles, newfile_path)
else:
print (cbfbm + u"的资料存在问题!")
elif (cg.endswith("打印包")):
lisDYpdf = self.getFilterFile(cg, u"完整包_1.pdf")
if (len(lisDYpdf) > 0):
for ls in lisDYpdf:
lsfilename = os.path.split(ls)
filename = lsfilename[1][0:18]
jh = self.getJHByCbfbm(listd, filename)
if jh.strip():
lsjh = jh.split("-")
listpath = ls.split("\\")
pdfname = "0" + lsjh[0] + "-2019-永久-确权登记类-" + lsjh[1]
newpath = os.path.join(savePath, listpath[1], listpath[2], listpath[3],
xq + "农经权档案数字化加工多页PDF", "0" + lsjh[0], "2019", "永久",
"确权登记类",
lsjh[1])
newfile_path = os.path.join(newpath, pdfname + ".pdf")
if (os.path.exists(newpath) == False):
os.makedirs(newpath)
shutil.copyfile(ls, newfile_path)
else:
err = u"未能找到承包方编码为" + filename + u"的件号,请检查电子表格中的承包方和件号的数据是否正确!"
print (err)
except Exception as r:
print('error %s' % r)
if __name__ == "__main__":
njhelper = NJHelper()
xiangz = ur"E:\**乡"
saveRoot = ur"F:\**乡成果"
xlspath = ur"E:\**乡\fc.xlsx"
xq = ur"**区"
allcf = []
allcfdic = []
filelistq = njhelper.getFilterFile(saveRoot, ".tif")
for allp in filelistq:
allcf.append(os.path.dirname(allp))
allcfdic = list(set(allcf))
allcfdic.sort(key=allcf.index)
del allcf, filelistq
gc.collect()
if len(allcfdic) > 0:
for allcfdicdir in allcfdic:
listtiff = njhelper.getFilterFile(allcfdicdir, ".tif")
savetiffpath = allcfdicdir.replace("**区农经权档案数字化加工单页TIFF", "**区农经权档案数字化加工多页TIFF")
filenamelis = savetiffpath.encode('utf-8').split('\\')
filename = filenamelis[-5] + "-" + filenamelis[-4] + "-" + filenamelis[-3] + "-" + filenamelis[-2] + "-" + \
filenamelis[-1] + ".tif"
if (os.path.exists(savetiffpath) == False):
os.makedirs(savetiffpath)
njhelper.addAllTiff(listtiff, os.path.join(savetiffpath, filename))
参考API:https://theiviaxx.github.io/photoshop-docs/Photoshop/; https://www.indesignjs.de/extendscriptAPI/photoshop2015.5/#ActionDescriptor.html; https://github.com/loonghao/photoshop-python-api。
不足:由于使用python2.7官方不在支持,本次采用py2exe打包为可执行的exe,虽然打包成功,但是无法运行,只能利用PyCharm调试运行,得到最终的成果,很是遗憾!
- 技术支持
如需获取相关包及源代码请加qq:1815222521。
|