python2.7开发photoshop一些经验
- 开发背景
原因:由于项目汇交的时候许多的成果需要转为pdf、tiff等,而且有严格的分辨率、压缩格式的要求,还要保证清晰度,因此许多的转换软件无法做到photoshop的效果,故而采用photoshop自动化输出。之前利用javascript开发photoshop,效果还不错,但是不能有创建文件夹,node.js也没能在photoshp中利用起来,折腾很久,最终放弃。
- 注意事项
开发环境:python2.7 + comtypes+photoshop2020+ PyCharm
注意:comtypes包安装及代码中使用到的包正确安装;photoshop也要正确安装。
- 案例
例子:
# -*- coding:utf-8 -*-
# @Time : 2022/5/7 15:50
# @Author : xys
# @Email : 1815222521@qq.com
# @File : PhotoShop.py
# @Software: PyCharm
# @Version : 1.0
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")
# 图片转Tiff
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()
# 图片转Tiff
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()
# 输入需要合并Tiff文件进行合并
def addAllTiff(self, listAllFile, SavePath):
newDoc = None
try:
# 合并图片的最大宽度作为合并文档的宽度
maxWidth = 0
# 合并图片的高度和作为合并文档的高度
totalHeight = 0
# 遍历文件夹下所有的文件
for pptfile in listAllFile:
# filepath = os.path.join(folderPath, pptfile)
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()
# 设置新