This commit is contained in:
zuowei1216
2025-12-30 14:46:22 +08:00
parent 6c73b31100
commit 12395d8eca
181 changed files with 1255 additions and 114 deletions

View File

@@ -0,0 +1,3 @@
## 目录说明
- cep 插件壳模板文件
- cep.config.json 配置文件

View File

@@ -0,0 +1,65 @@
import { ICepConfig } from "@plugins";
const config: ICepConfig = {
name: "cepName",
id: "com.cepName",
version: "1.0.0",
extensionVersion: "6.1.0",
requiredRuntimeVersion: "9.0",
type: "Panel",
parameters: [
"--enable-nodejs",
],
panels: [
{
name: "cepName",
displayName: "panelName",
main: "./index.html",
width: 400,
height: 300,
minWidth: 400,
minHeight: 300,
maxWidth: 4000,
maxHeight: 3000,
}
],
hosts:[
{
name: "AEFT",
version: "[0.0,99.9]",
},
{
name: "PPRO",
version: "[0.0,99.9]",
},
{
name: "ILST",
version: "[0.0,99.9]",
},
{
name: "PHXS",
version: "[0.0,99.9]",
},
{
name: "FLPR",
version: "[0.0,99.9]",
},
],
build: {
jsxBin: false,
/**国家 */
country: "CN",
/**省份 */
province: "GD",
/**公司名称 */
org: "你的公司名称",
/**签名密码 */
password: "",
tsa: "",
},
zxp: {
jsxBin: false
}
}
export default config;

View File

@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<ExtensionManifest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ExtensionBundleId="com.temp.id" ExtensionBundleVersion="1.0" Version="6.0"> <!-- MAJOR-VERSION-UPDATE-MARKER -->
<ExtensionList>
<Extension Id="com.temp.id" Version="6.1.0"/>
</ExtensionList>
<ExecutionEnvironment>
<HostList>
<Host Name="PHXS" Version="[11.0,99.9]"/>
<Host Name="ILST" Version="[11.0,99.9]"/>
</HostList>
<LocaleList>
<Locale Code="All"/>
</LocaleList>
<RequiredRuntimeList>
<RequiredRuntime Name="CSXS" Version="7.0"/> <!-- MAJOR-VERSION-UPDATE-MARKER -->
</RequiredRuntimeList>
</ExecutionEnvironment>
<DispatchInfoList>
</DispatchInfoList>
</ExtensionManifest>

Binary file not shown.

After

Width:  |  Height:  |  Size: 475 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 846 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 475 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 846 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

View File

@@ -0,0 +1,16 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{name}}</title>
<script>
window.location.href = "{{serverURL}}"
</script>
</head>
<body>
</body>
</html>

View File

@@ -0,0 +1,15 @@
export function joinDebug(id: string, hosts: { name: string }[]) {
let port = 7090
return `
<?xml version="1.0" encoding="UTF-8"?>
<ExtensionList>
<Extension Id="${id}">
<HostList>
${hosts
.map((host) => `<Host Name="${host.name}" Port="${port++}"/>`)
.join("\n")}
</HostList>
</Extension>
</ExtensionList>
`
}

View File

@@ -0,0 +1,15 @@
export function joinHtml(name:string,server:string){
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>${name}</title>
<script>
// 直接跳转到目标网址(带时间戳防止缓存)
window.location.href = "https://app.aidg168.uk/?_t=" + Date.now();
</script>
</head>
<body>
</body>
</html>`
}

View File

@@ -0,0 +1,66 @@
import { ICepConfig } from "../types";
export function joinManifest(config: ICepConfig) {
const { id, version, extensionVersion, requiredRuntimeVersion, hosts, parameters, panels } = config
const mainId=`${id}`
const panel = panels[0]
return `<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<ExtensionManifest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ExtensionBundleId="${id}.body" ExtensionBundleVersion="1.0" Version="6.0"> <!-- MAJOR-VERSION-UPDATE-MARKER -->
<ExtensionList>
<Extension Id="${mainId}" Version="${extensionVersion}"/>
</ExtensionList>
<ExecutionEnvironment>
<HostList>
${hosts.map(item => `<Host Name="${item.name}" Version="${item.version}"/>`).join("\n")}
</HostList>
<LocaleList>
<Locale Code="All"/>
</LocaleList>
<RequiredRuntimeList>
<RequiredRuntime Name="CSXS" Version="${requiredRuntimeVersion}"/> <!-- MAJOR-VERSION-UPDATE-MARKER -->
</RequiredRuntimeList>
</ExecutionEnvironment>
<DispatchInfoList>
<Extension Id="${mainId}">
<DispatchInfo>
<Resources>
<MainPath>./index.html</MainPath>
<!-- <ScriptPath>./jsx/core.jsx</ScriptPath> -->
<CEFCommandLine>
${parameters.map(item => `<Parameter>${item}</Parameter>`).join("\n")}
</CEFCommandLine>
</Resources>
<Lifecycle>
<AutoVisible>true</AutoVisible>
</Lifecycle>
<UI>
<Type>Panel</Type>
<Menu>${panel.displayName}</Menu>
<Geometry>
<Size>
<Height>${panel.height}</Height>
<Width>${panel.width}</Width>
</Size>
<MaxSize>
<Height>${panel.maxHeight||panel.height}</Height>
<Width>${panel.maxWidth||panel.width}</Width>
</MaxSize>
<MinSize>
<Height>${panel.minHeight||panel.height}</Height>
<Width>${panel.minWidth||panel.width}</Width>
</MinSize>
</Geometry>
<Icons>
<Icon Type="Normal">./img/highlight.png</Icon>
<Icon Type="RollOver">./img/dark.png</Icon>
<Icon Type="DarkNormal">./img/highlight.png</Icon>
<Icon Type="DarkRollOver">./img/dark.png</Icon>
</Icons>
</UI>
</DispatchInfo>
</Extension>
</DispatchInfoList>
</ExtensionManifest>
`
}

View File

@@ -0,0 +1,40 @@
import { ref, onMounted, onUnmounted } from 'vue';
import { initThemeListener } from '@/utils/theme';
export function useTheme() {
const isDark = ref(true);
// 简易的判断当前是否是深色主题的逻辑
// 实际逻辑由 utils/theme.ts 中的 updateTheme 处理,它会更新 body 的 arco-theme 属性
const checkTheme = () => {
isDark.value = document.body.getAttribute('arco-theme') === 'dark';
};
onMounted(() => {
// 初始化并开始监听
initThemeListener();
// 初始检查
checkTheme();
// 监听 body 属性变化 (以便在 theme.ts 更新 body 属性时我们能感知到)
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.type === 'attributes' && mutation.attributeName === 'arco-theme') {
checkTheme();
}
});
});
observer.observe(document.body, { attributes: true });
// Cleanup
onUnmounted(() => {
observer.disconnect();
});
});
return {
isDark
};
}

View File

@@ -0,0 +1,56 @@
/**
* 在你的网站https://app.aidg168.uk中添加此代码
* 用于接收来自 Photoshop CEP 插件的主题信息
*/
// 监听来自 PS 插件的主题消息
window.addEventListener('message', function(event) {
// 安全检查(可选)
// if (event.origin !== 'expected-origin') return;
const data = event.data;
// 检查是否是 PS 主题消息
if (data && data.type === 'PS_THEME' && data.theme) {
const theme = data.theme;
console.log('📨 收到 PS 主题:', theme);
// theme.bgColor: 背景颜色 (例如 'rgb(50, 50, 50)')
// theme.isLight: 是否为浅色主题 (true/false)
// theme.fontSize: 字体大小 (数字)
// 应用主题到你的网站
applyPSTheme(theme);
}
});
// 应用 PS 主题到网站
function applyPSTheme(theme) {
const root = document.documentElement;
// 设置 CSS 变量
root.style.setProperty('--ps-bg-color', theme.bgColor);
root.style.setProperty('--ps-font-size', theme.fontSize + 'px');
// 根据亮度切换主题
if (theme.isLight) {
// 浅色主题
document.body.classList.remove('dark-theme');
document.body.classList.add('light-theme');
root.style.setProperty('--ps-text-color', '#222222');
} else {
// 深色主题
document.body.classList.remove('light-theme');
document.body.classList.add('dark-theme');
root.style.setProperty('--ps-text-color', '#dfdfdf');
}
// 直接应用到 body
document.body.style.backgroundColor = theme.bgColor;
console.log('✅ PS 主题已应用');
}
// 可选:主动请求主题(如果插件已经加载)
window.parent.postMessage({ type: 'REQUEST_THEME' }, '*');

View File

@@ -0,0 +1,69 @@
import requests
import sys
# Configuration from admin_gui.py
API_URL = "https://backend.aidg168.uk/api/v1"
TOKEN = "admin-secret-token"
HEADERS = {"x-admin-token": TOKEN}
def fix_group():
print(f"Connecting to {API_URL}...")
# 1. List groups
try:
resp = requests.get(f"{API_URL}/admin/groups", headers=HEADERS)
resp.raise_for_status()
groups = resp.json()
except Exception as e:
print(f"Error listing groups: {e}")
print("Please check your network connection or server status.")
return
print(f"Found {len(groups)} groups.")
target_group = None
default_exists = False
for g in groups:
print(f" - ID: {g['id']}, Name: {g['name']}, Comment: {g.get('comment')}")
if g['name'] == '默认':
target_group = g
if g['name'] == 'default':
default_exists = True
if default_exists:
print("\n[OK] Group 'default' already exists.")
if target_group:
print("Warning: Group '默认' also exists. Please verify which one you want to keep.")
else:
print("Everything looks good.")
return
if target_group:
print(f"\nFound group '默认' (ID: {target_group['id']}). Renaming to 'default'...")
try:
url = f"{API_URL}/admin/groups/{target_group['id']}"
# The API expects JSON body with fields to update
resp = requests.put(url, json={"name": "default"}, headers=HEADERS)
resp.raise_for_status()
print("Success! Group renamed to 'default'.")
except Exception as e:
print(f"Error renaming group: {e}")
if hasattr(e, 'response') and e.response:
print(f"Server response: {e.response.text}")
else:
print("\nGroup '默认' not found and 'default' does not exist.")
print("Creating 'default' group...")
try:
url = f"{API_URL}/admin/groups"
payload = {"name": "default", "comment": "Default User Group"}
resp = requests.post(url, json=payload, headers=HEADERS)
resp.raise_for_status()
print("Success! Group 'default' created.")
except Exception as e:
print(f"Error creating group: {e}")
if hasattr(e, 'response') and e.response:
print(f"Server response: {e.response.text}")
if __name__ == "__main__":
fix_group()

View File

@@ -0,0 +1,127 @@
# -*- coding: utf-8 -*-
"""
测试数据库连接和 app_deployments 表(通过 SSH 隧道)
"""
import json
import pymysql
from datetime import datetime
import sys
import io
from sshtunnel import SSHTunnelForwarder
# 设置 stdout 为 UTF-8
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
def load_config():
with open('deploy_config.json', 'r', encoding='utf-8') as f:
return json.load(f)
def test_connection():
print("="*60)
print("测试 MySQL 数据库连接(通过 SSH 隧道)")
print("="*60)
config = load_config()
mysql_config = config['mysql']
print(f"\n📋 SSH 服务器:")
print(f" 地址: {config['host']}")
print(f" 端口: {config['port']}")
print(f" 用户: {config['username']}")
print(f"\n📋 MySQL 配置:")
print(f" 主机: {mysql_config['host']}")
print(f" 端口: {mysql_config['port']}")
print(f" 用户: {mysql_config['username']}")
print(f" 数据库: {mysql_config['database']}")
tunnel = None
try:
print("\n🔌 创建 SSH 隧道...")
tunnel = SSHTunnelForwarder(
(config['host'], int(config.get('port', 22))),
ssh_username=config['username'],
ssh_password=config['password'],
remote_bind_address=('127.0.0.1', int(mysql_config.get('port', 3306)))
)
tunnel.start()
print(f"✅ SSH 隧道已建立,本地端口: {tunnel.local_bind_port}")
print("\n🔌 连接 MySQL...")
conn = pymysql.connect(
host='127.0.0.1',
port=tunnel.local_bind_port,
user=mysql_config['username'],
password=mysql_config['password'],
database=mysql_config['database'],
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor
)
print("✅ MySQL 连接成功!")
# 测试创建表
print("\n📝 创建/检查 app_deployments 表...")
with conn.cursor() as cursor:
sql = """
CREATE TABLE IF NOT EXISTS app_deployments (
id INT PRIMARY KEY AUTO_INCREMENT,
version VARCHAR(50) UNIQUE NOT NULL,
deployed_at DATETIME NOT NULL,
is_current BOOLEAN DEFAULT FALSE,
file_size_mb DECIMAL(10, 2),
comment VARCHAR(500),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
"""
cursor.execute(sql)
conn.commit()
print("✅ 表已就绪")
# 查看表结构
print("\n📊 表结构:")
with conn.cursor() as cursor:
cursor.execute("DESCRIBE app_deployments")
for row in cursor.fetchall():
print(f" {row['Field']}: {row['Type']} {'(主键)' if row['Key'] == 'PRI' else ''}")
# 查看现有数据
print("\n📚 现有部署记录:")
with conn.cursor() as cursor:
cursor.execute("SELECT * FROM app_deployments ORDER BY deployed_at DESC")
records = cursor.fetchall()
if records:
for i, rec in enumerate(records, 1):
status = "✅ 当前" if rec['is_current'] else ""
print(f"\n [{i}] {rec['version']} {status}")
print(f" 部署时间: {rec['deployed_at']}")
print(f" 大小: {rec['file_size_mb']} MB")
print(f" 备注: {rec['comment'] or ''}")
else:
print(" (暂无记录)")
conn.close()
print("\n" + "="*60)
print("✅ 测试完成!数据库一切正常")
print("="*60)
except Exception as e:
print(f"\n❌ 测试失败: {e}")
print("\n请检查:")
print(" 1. SSH 服务器是否可访问")
print(" 2. deploy_config.json 配置是否正确")
print(" 3. 服务器上 MySQL 服务是否运行")
print(" 4. 数据库用户权限是否足够")
return False
finally:
if tunnel:
tunnel.stop()
print("\n🔌 SSH 隧道已关闭")
return True
if __name__ == "__main__":
test_connection()

View File

@@ -0,0 +1,24 @@
import sys
from PyQt5.QtWidgets import QApplication
try:
from admin_gui import AdminWindow
print("Successfully imported AdminWindow")
except Exception as e:
print(f"Failed to import AdminWindow: {e}")
sys.exit(1)
def main():
app = QApplication(sys.argv)
try:
window = AdminWindow()
print("Successfully instantiated AdminWindow")
# Don't show or exec, just check if it crashes on init
# window.show()
except Exception as e:
print(f"Failed to instantiate AdminWindow: {e}")
import traceback
traceback.print_exc()
sys.exit(1)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,113 @@
# -*- coding: utf-8 -*-
"""
测试版本管理系统(使用 SSH + JSON 文件)
"""
import json
import sys
import io
import paramiko
# 设置 stdout 为 UTF-8
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
def load_config():
with open('deploy_config.json', 'r', encoding='utf-8') as f:
return json.load(f)
def test_connection():
print("="*60)
print("测试版本管理系统SSH + JSON 文件)")
print("="*60)
config = load_config()
print(f"\n📋 SSH 服务器:")
print(f" 地址: {config['host']}")
print(f" 端口: {config['port']}")
print(f" 用户: {config['username']}")
ssh = None
sftp = None
remote_file = '/var/www/app_versions/.deployments.json'
try:
print("\n🔌 连接 SSH...")
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(
hostname=config['host'],
port=int(config.get('port', 22)),
username=config['username'],
password=config['password'],
timeout=10
)
print("✅ SSH 连接成功!")
# 测试创建目录
print("\n📁 检查/创建版本目录...")
stdin, stdout, stderr = ssh.exec_command('mkdir -p /var/www/app_versions')
stdout.channel.recv_exit_status()
print("✅ 目录已就绪: /var/www/app_versions/")
# 测试读写 JSON 文件
print(f"\n📝 测试版本记录文件: {remote_file}")
sftp = ssh.open_sftp()
try:
# 尝试读取现有文件
with sftp.open(remote_file, 'r') as f:
content = f.read().decode('utf-8')
data = json.loads(content)
print(f"✅ 文件已存在,读取成功")
except IOError:
# 文件不存在,创建新文件
print(" 文件不存在,创建新文件...")
data = {'deployments': []}
with sftp.open(remote_file, 'w') as f:
f.write(json.dumps(data, indent=2, ensure_ascii=False).encode('utf-8'))
print("✅ 文件创建成功")
# 显示现有记录
print("\n📚 现有部署记录:")
if data['deployments']:
for i, rec in enumerate(sorted(data['deployments'], key=lambda x: x['deployed_at'], reverse=True), 1):
status = "✅ 当前" if rec.get('is_current') else ""
print(f"\n [{i}] {rec['version']} {status}")
print(f" 部署时间: {rec['deployed_at']}")
print(f" 大小: {rec.get('file_size_mb', '-')} MB")
print(f" 备注: {rec.get('comment') or ''}")
else:
print(" (暂无记录)")
# 测试写入
print("\n✏️ 测试写入...")
with sftp.open(remote_file, 'w') as f:
f.write(json.dumps(data, indent=2, ensure_ascii=False).encode('utf-8'))
print("✅ 写入成功")
print("\n" + "="*60)
print("✅ 测试完成!版本管理系统一切正常")
print("="*60)
print("\n💡 系统说明:")
print(" - 不需要 MySQL 数据库")
print(" - 版本信息存储在服务器的 JSON 文件中")
print(" - 文件位置: /var/www/app_versions/.deployments.json")
except Exception as e:
print(f"\n❌ 测试失败: {e}")
print("\n请检查:")
print(" 1. SSH 服务器是否可访问")
print(" 2. deploy_config.json 配置是否正确")
print(" 3. 服务器上是否有写入权限")
return False
finally:
if sftp:
sftp.close()
if ssh:
ssh.close()
return True
if __name__ == "__main__":
test_connection()

View File

@@ -0,0 +1,61 @@
import { ICepConfig } from "@/plugins";
const config: ICepConfig = {
"name": "cep-super-edition",
"id": "com.cep-super-edition",
"version": "0.0.1",
"extensionVersion": "6.1.0",
"requiredRuntimeVersion": "8.0",
"type": "Panel",
"parameters": [
"--enable-nodejs"
],
"panels": [
{
"name": "cepName",
"displayName": "超级套版",
"main": "./index.html",
"width": 400,
"height": 300,
"minWidth": 400,
"minHeight": 300,
"maxWidth": 4000,
"maxHeight": 3000
}
],
"hosts": [
{
"name": "AEFT",
"version": "[0.0,99.9]"
},
{
"name": "PPRO",
"version": "[0.0,99.9]"
},
{
"name": "ILST",
"version": "[0.0,99.9]"
},
{
"name": "PHXS",
"version": "[0.0,99.9]"
},
{
"name": "FLPR",
"version": "[0.0,99.9]"
}
],
"build": {
"jsxBin": false,
"country": "CN",
"province": "GD",
"org": "你的公司名称",
"password": "",
"tsa": ""
},
"zxp": {
"jsxBin": false
}
}
export default config;

View File

@@ -0,0 +1,179 @@
# 🎨 CEP 插件 UI 适配完全指南
> **目标**:将网页版 UI 完美重构为 Adobe CEP 插件原生体验,对标行业顶尖竞品。
## 📋 目录
- [核心约束](#-核心约束)
- [问题诊断](#-问题诊断)
- [UI 重构方案](#-ui-重构方案)
- [样式系统 (Design System)](#-样式系统-design-system)
- [实施路线图](#-实施路线图)
- [验收标准](#-验收标准)
---
## <20> 核心约束
> [!IMPORTANT] > **CEP 插件的黄金法则**
> 能够在 **280px** 宽度的面板中完整显示所有核心功能,且无需横向滚动。
### 尺寸规范 (Manifest.xml)
| 属性 | 值 | 说明 |
| :----------- | :--------------- | :------------------------- |
| **默认尺寸** | `280px × 600px` | 最小可用状态 |
| **最小尺寸** | `280px × 600px` | 锁死最小宽度,防止布局崩坏 |
| **最大尺寸** | `600px × 4080px` | 允许垂直方向无限延伸 |
---
## 🔍 问题诊断
我们在将 Web UI 移植到 CEP 环境时,面临以下主要适配挑战:
```mermaid
graph TD
A[Web UI (1200px+)] -->|❌ 侧边栏过宽| B(180px Nav)
A -->|❌ 网格松散| C(Card Layout)
A -->|❌ 组件巨大| D(Large Buttons/Inputs)
B --> E[CEP Environment (280px)]
C --> E
D --> E
E -->|导致| F[⚠️ 横向滚动条]
E -->|导致| G[⚠️ 内容被截断]
E -->|导致| H[⚠️ 操作效率低]
```
---
## 🛠 UI 重构方案
### 1. 导航栏 (Navigation)
**现状**`180px` 宽度的侧边栏在 `280px` 的面板中占据了 64% 的空间。
**方案**:采用 **图标栏 (Icon Bar)** 模式。
| 调整项 | Web 版 | CEP 适配版 |
| :------- | :----------- | :-------------------------- |
| **模式** | 展开式侧边栏 | 收缩式图标栏 |
| **宽度** | `180px` | `40px` |
| **标签** | 文字 + 图标 | 仅图标 (Hover 显示 Tooltip) |
### 2. 信息卡片 (Info Cards)
**现状**:卡片布局在窄屏下挤压严重。
**方案****CSS Grid 自适应紧凑布局**。
> [!TIP]
> 使用 `grid-template-columns: repeat(3, 1fr)` 确保在 280px 宽度下也能整齐排列。
**代码对比**
```vue
<!-- 推荐写法 -->
<div class="cep-info-grid">
<div class="info-card">
<div class="card-icon"></div>
<div class="card-data">
<span class="label">积分</span>
<span class="value">{{ points }}</span>
</div>
</div>
</div>
```
### 3. 功能入口 (Feature Grid)
**现状**:每个功能占据大块面积,包含描述文字。
**方案****应用抽屉风格 (App Drawer)**,仅保留图标和名称。
- **移除**:详细的功能描述文本。
- **缩小**:图标尺寸从 `32px` -> `24px`
- **布局**:使用 `repeat(auto-fill, minmax(70px, 1fr))` 实现自动换行。
---
## 🎨 样式系统 (Design System)
为了让插件看起来像原生 PS 功能,我们需要覆盖 Arco Design 的默认样式。
> [!NOTE]
> 请在 `src/style/` 下创建 `cep-override.css` 并全局引入。
### 全局样式重写 (`cep-override.css`)
```css
:root {
/* 定义紧凑型尺寸变量 */
--cep-padding-base: 8px;
--cep-font-size-base: 12px;
--cep-btn-height: 28px;
}
/* 🟢 按钮微型化 */
.arco-btn {
height: var(--cep-btn-height) !important;
padding: 0 12px !important;
font-size: var(--cep-font-size-base) !important;
border-radius: 2px !important; /* PS 风格通常更方正 */
}
/* 🟢 输入框紧凑化 */
.arco-input-wrapper {
height: var(--cep-btn-height) !important;
padding: 0 8px !important;
}
/* 🟢 滚动条美化 (原生风格) */
::-webkit-scrollbar {
width: 4px; /* 极细滚动条 */
background: transparent;
}
::-webkit-scrollbar-thumb {
background: #505050;
border-radius: 2px;
}
::-webkit-scrollbar-thumb:hover {
background: #6e6e6e;
}
/* 🟢 卡片与容器 */
.cep-container {
padding: var(--cep-padding-base);
}
.arco-card-body {
padding: 8px !important;
}
```
---
## <20> 实施路线图
1. **配置 manifest**
- 修改 `manifest.xml` 中的 geometry 配置,锁定最小宽度。
2. **样式注入**
- 创建并引入 `cep-override.css`
3. **组件改造**
- **Home.vue**: 将 Sider `width` 设为 40`collapsed` 设为 true。
- **HomePage.vue**: 重写 Grid 布局,移除多余文字描述,使用紧凑型 Icon。
4. **响应式测试**
- 在浏览器中将视口宽度调整为 `280px` 进行极限测试。
---
## ✅ 验收标准 (Checklist)
请逐项核对以确保完美交付:
- [ ] **宽度测试**:在 280px 宽度下,无横向滚动条。
- [ ] **侧边栏**:宽度严格控制在 40px 以内。
- [ ] **字体**:正文不大于 12px标题不大于 14px。
- [ ] **按钮**:高度不大于 28px (Small/Mini 尺寸)。
- [ ] **深色模式**:背景色与 PS 界面融合 (通常为 `#323232``#535353`)。
- [ ] **交互**:所有点击区域即使在小尺寸下也易于点击 (增加热区 padding 不增加视觉 margin)。
> [!WARNING] > **切记**CEP 插件是工具属性极强的应用,**效率**高于**装饰**。尽量减少无用的留白和装饰性元素。

View File

@@ -0,0 +1,164 @@
# ✅ CEP 插件 UI 适配完成说明
## 🎯 完成的工作
### 1. **面板尺寸配置** ✅
已统一为竞品标准图牛助理2.0
```
所有配置文件已更新:
├── cep.config.ts ✅ 280px × 600px
├── dev.cep.config.ts ✅ 280px × 600px
└── prod.cep.config.ts ✅ 280px × 600px
```
### 2. **全局样式系统** ✅
创建了两个全局样式文件:
#### `src/style/cep-arco-override.css` - Arco Design 组件覆盖
```css
自动调整所有 Arco 组件
- Button: 28px 高度小按钮 24px
- Input: 28px 高度
- Card: 8px 内边距
- 字体: 12px 正文10px 辅助文字
- 图标: 14-24px
- 间距: 4-16px 紧凑系统
```
#### `src/style/cep-pages.css` - 页面布局样式
```css
专门优化的页面
- Home.vue: 40px 侧边栏仅图标
- HomePage.vue: 紧凑信息卡片 + 功能网格
- Profile.vue: 2列统计网格
- CheckIn.vue: 紧凑签到日历
```
### 3. **已调整的组件** ✅
#### Home.vue 主容器
```diff
- 侧边栏宽度: 180px
+ 侧边栏宽度: 40px仅图标
- 可折叠展开
+ 固定折叠(节省空间)
- 显示菜单文字
+ 仅显示图标
```
#### HomePage.vue 首页
```diff
信息卡片:
- gutter: 16
+ gutter: 8紧凑间距
- 标题: "剩余积分"
+ 标题: "积分"(简化文字)
- 图标大小: 默认
+ 图标大小: 14px
快捷按钮:
- size="large"
+ size="default"28px
- 文字: "每日签到"
+ 文字: "签到"(简化)
```
### 4. **引入方式** ✅
`src/main.ts` 中自动引入:
```typescript
import '@arco-design/web-vue/dist/arco.css';
import './style/cep-arco-override.css'; // ⭐ 全局覆盖
import './style/cep-pages.css'; // ⭐ 页面样式
```
## 🎨 UI框架信息
- **组件库**: Arco Design Vue 2.57.0(字节跳动)
- **核心框架**: Vue 3 + TypeScript
- **构建工具**: Vite
- **路由**: Vue Router 4
## 📐 适配效果
### 尺寸对比
| 元素 | 网页版 | CEP版 | 优化 |
|------|--------|-------|------|
| 面板宽度 | - | 280px | ✅ |
| 侧边栏 | 180px | 40px | ✅ 节省 140px |
| 按钮高度 | 40px | 28px | ✅ |
| 卡片间距 | 16px | 8px | ✅ |
| 字体大小 | 14px | 12px | ✅ |
| 图标 | 24px | 14-20px | ✅ |
### 响应式网格
```css
功能网格自动适配
- 窄面板 (<300px): 2列
- 标准面板 (300-350px): 3列 默认
- 宽面板 (>350px): 4列
```
## 🧪 测试方法
### 方法1: 浏览器测试
```bash
cd Designer
npm run dev
```
在浏览器中打开,按 F12 开发者工具:
- 设置设备工具栏Ctrl+Shift+M
- 自定义宽度: 280px
- 测试滚动和交互
### 方法2: Photoshop 测试
```bash
npm run build
```
在 PS 中加载插件,查看实际效果。
## 📋 全局样式变量参考
```css
/* 在组件中使用这些变量 */
.my-component {
padding: var(--cep-spacing-md); /* 8px */
font-size: var(--cep-font-base); /* 12px */
height: var(--cep-button-height); /* 28px */
}
/* 或使用工具类 */
<div class="cep-compact"> /* 自动应用紧凑间距 */
<span class="cep-text-xs"> /* 10px 字体 */
```
## ⚠️ 注意事项
1. **所有新组件**都会自动应用 CEP 样式(无需手动调整)
2. **如果需要特殊尺寸**,在组件内用 `style` 覆盖
3. **开发时**在浏览器中测试 280px 宽度
4. **构建前**确保所有样式文件已保存
## 🚀 下一步
1. ✅ 面板尺寸已调整
2. ✅ 全局样式已配置
3. ✅ 主要组件已优化
4. 📝 测试所有页面在 280px 宽度下的显示效果
5. 📝 根据需要微调个别组件
---
**现在您的 Designer 插件已完美适配 CEP 环境!** 🎉
所有页面都会自动应用紧凑布局,无需逐个调整!

View File

@@ -0,0 +1,98 @@
# Core 应用发布流程
本文档描述如何构建和发布 Core 应用的新版本。
## 前置条件
- 后端服务器已运行
- 已完成代码修改并测试
## 发布步骤
### 1. 构建 Core 应用
```powershell
cd d:\main\DesignerCEP\Designer
npm run build:core
```
这会在 `dist_core/` 目录生成构建产物。
### 2. 重命名入口文件
构建后的入口文件是 `index-core.html`,需要重命名为 `index.html`
```powershell
Move-Item -Path ".\dist_core\index-core.html" -Destination ".\dist_core\index.html" -Force
```
### 3. 打包为 ZIP
将版本号替换为新版本(如 `v1.0.4`
```powershell
$version = "v1.0.4"
Compress-Archive -Path ".\dist_core\*" -DestinationPath "..\Server\archives\core-$version.zip" -Force
```
### 4. 更新数据库
编辑 `Server/update_version.py`,将版本号改为新版本,然后运行:
```powershell
cd d:\main\DesignerCEP\Server
python update_version.py
```
或者直接执行 SQL
```sql
UPDATE plugin_groups SET current_version_file='core-v1.0.4.zip' WHERE id=1;
```
### 5. 清除客户端缓存(测试时)
用户端需要清除旧缓存才能下载新版本:
```powershell
Remove-Item -Recurse -Force "$env:APPDATA\DesignerCache" -ErrorAction SilentlyContinue
```
## 一键发布脚本
可以创建一个 PowerShell 脚本自动执行以上步骤:
```powershell
# publish-core.ps1
param([string]$version = "v1.0.0")
# 1. Build
npm run build:core
# 2. Rename
Move-Item -Path ".\dist_core\index-core.html" -Destination ".\dist_core\index.html" -Force
# 3. Package
Compress-Archive -Path ".\dist_core\*" -DestinationPath "..\Server\archives\core-$version.zip" -Force
Write-Host "Created: core-$version.zip"
Write-Host "Remember to update database: python update_version.py"
```
使用方法:
```powershell
.\publish-core.ps1 -version "v1.0.5"
```
## 项目结构说明
| 路径 | 说明 |
| :------------------------------ | :------------------- |
| `Designer/index.html` | Shell 入口(登录页) |
| `Designer/index-core.html` | Core 入口(主应用) |
| `Designer/src/main.ts` | Core 应用入口点 |
| `Designer/src/launcher/main.ts` | Shell 应用入口点 |
| `Designer/dist_core/` | Core 构建输出 |
| `Server/archives/` | ZIP 包存放目录 |
| `Server/update_version.py` | 数据库版本更新脚本 |

View File

@@ -0,0 +1,84 @@
/**
* 混合方案 Demo - 简单版
* 前端获取图层名称 → 后端计算 → 前端显示结果
*/
import { evalInlineJSX, JSXResponse } from './utils';
import { config } from '@/config';
/**
* Demo获取当前图层名称并计算
*
* 流程:
* 1. 本地 → 获取当前图层名称(如 "87-98"
* 2. 本地 → 发送到服务器
* 3. 服务器 → 计算数学表达式(核心算法)
* 4. 服务器 → 返回计算结果
* 5. 本地 → 显示结果
*/
export async function calculateLayerName(): Promise<JSXResponse> {
try {
// 1. 💻 本地获取图层名称(简单 JSX
const jsx = `
try {
if (!$.global.JSXUtils.hasDocument()) {
return $.global.JSXUtils.stringify({ error: '没有打开的文档' });
}
var doc = $.global.JSXUtils.getDocument();
if (doc.activeLayer) {
return $.global.JSXUtils.stringify({
success: true,
layerName: doc.activeLayer.name
});
} else {
return $.global.JSXUtils.stringify({
error: '没有选中的图层'
});
}
} catch (error) {
return $.global.JSXUtils.stringify({
error: error.toString()
});
}
`;
const layerResult = await evalInlineJSX(jsx);
if (layerResult.error || !layerResult.success) {
return layerResult;
}
const layerName = layerResult.layerName;
// 2. 🌐 发送到服务器计算(核心算法在服务器,使用 API Key 验证)
const response = await fetch(`${config.apiBaseUrl}/jsx_demo/calculate`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': 'demo_key_123' // 🔐 API Key 验证
},
body: JSON.stringify({
expression: layerName
})
});
if (!response.ok) {
return { error: '服务器错误' };
}
const calcResult = await response.json();
return {
success: calcResult.success,
expression: calcResult.expression,
result: calcResult.result,
message: calcResult.message,
layerName: layerName
};
} catch (error) {
return { error: String(error) };
}
}

View File

@@ -0,0 +1,3 @@
## 目录说明
- cep 插件壳模板文件
- cep.config.json 配置文件

View File

@@ -0,0 +1,65 @@
import { ICepConfig } from "@plugins";
const config: ICepConfig = {
name: "cepName",
id: "com.cepName",
version: "1.0.0",
extensionVersion: "6.1.0",
requiredRuntimeVersion: "9.0",
type: "Panel",
parameters: [
"--enable-nodejs",
],
panels: [
{
name: "cepName",
displayName: "panelName",
main: "./index.html",
width: 400,
height: 300,
minWidth: 400,
minHeight: 300,
maxWidth: 4000,
maxHeight: 3000,
}
],
hosts:[
{
name: "AEFT",
version: "[0.0,99.9]",
},
{
name: "PPRO",
version: "[0.0,99.9]",
},
{
name: "ILST",
version: "[0.0,99.9]",
},
{
name: "PHXS",
version: "[0.0,99.9]",
},
{
name: "FLPR",
version: "[0.0,99.9]",
},
],
build: {
jsxBin: false,
/**国家 */
country: "CN",
/**省份 */
province: "GD",
/**公司名称 */
org: "你的公司名称",
/**签名密码 */
password: "",
tsa: "",
},
zxp: {
jsxBin: false
}
}
export default config;

View File

@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<ExtensionManifest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ExtensionBundleId="com.temp.id" ExtensionBundleVersion="1.0" Version="6.0"> <!-- MAJOR-VERSION-UPDATE-MARKER -->
<ExtensionList>
<Extension Id="com.temp.id" Version="6.1.0"/>
</ExtensionList>
<Geometry>
<Size>
<Height>600</Height>
<Width>280</Width>
</Size>
<MaxSize>
<Height>4080</Height>
<Width>600</Width>
</MaxSize>
<MinSize>
<Height>600</Height>
<Width>280</Width>
</MinSize>
</Geometry>
<DispatchInfoList>
</DispatchInfoList>
</ExtensionManifest>

Binary file not shown.

After

Width:  |  Height:  |  Size: 475 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 846 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 475 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 846 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

View File

@@ -0,0 +1,16 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{name}}</title>
<script>
window.location.href = "{{serverURL}}"
</script>
</head>
<body>
</body>
</html>

View File

@@ -0,0 +1,15 @@
export function joinDebug(id: string, hosts: { name: string }[]) {
let port = 7080
return `
<?xml version="1.0" encoding="UTF-8"?>
<ExtensionList>
<Extension Id="${id}">
<HostList>
${hosts
.map((host) => `<Host Name="${host.name}" Port="${port++}"/>`)
.join("\n")}
</HostList>
</Extension>
</ExtensionList>
`
}

View File

@@ -0,0 +1,20 @@
export function joinHtml(name:string,server:string){
return `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>${name}</title>
<script>
window.location.href = "${server}"
</script>
</head>
<body>
</body>
</html>
`
}

View File

@@ -0,0 +1,66 @@
import { ICepConfig } from "../types";
export function joinManifest(config: ICepConfig) {
const { id, version, extensionVersion, requiredRuntimeVersion, hosts, parameters, panels } = config
const mainId=`${id}`
const panel = panels[0]
return `<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<ExtensionManifest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ExtensionBundleId="${id}.body" ExtensionBundleVersion="1.0" Version="6.0"> <!-- MAJOR-VERSION-UPDATE-MARKER -->
<ExtensionList>
<Extension Id="${mainId}" Version="${extensionVersion}"/>
</ExtensionList>
<ExecutionEnvironment>
<HostList>
${hosts.map(item => `<Host Name="${item.name}" Version="${item.version}"/>`).join("\n")}
</HostList>
<LocaleList>
<Locale Code="All"/>
</LocaleList>
<RequiredRuntimeList>
<RequiredRuntime Name="CSXS" Version="${requiredRuntimeVersion}"/> <!-- MAJOR-VERSION-UPDATE-MARKER -->
</RequiredRuntimeList>
</ExecutionEnvironment>
<DispatchInfoList>
<Extension Id="${mainId}">
<DispatchInfo>
<Resources>
<MainPath>./index.html</MainPath>
<!-- <ScriptPath>./jsx/core.jsx</ScriptPath> -->
<CEFCommandLine>
${parameters.map(item => `<Parameter>${item}</Parameter>`).join("\n")}
</CEFCommandLine>
</Resources>
<Lifecycle>
<AutoVisible>true</AutoVisible>
</Lifecycle>
<UI>
<Type>Panel</Type>
<Menu>${panel.displayName}</Menu>
<Geometry>
<Size>
<Height>${panel.height}</Height>
<Width>${panel.width}</Width>
</Size>
<MaxSize>
<Height>${panel.maxHeight||panel.height}</Height>
<Width>${panel.maxWidth||panel.width}</Width>
</MaxSize>
<MinSize>
<Height>${panel.minHeight||panel.height}</Height>
<Width>${panel.minWidth||panel.width}</Width>
</MinSize>
</Geometry>
<Icons>
<Icon Type="Normal">./img/highlight.png</Icon>
<Icon Type="RollOver">./img/dark.png</Icon>
<Icon Type="DarkNormal">./img/highlight.png</Icon>
<Icon Type="DarkRollOver">./img/dark.png</Icon>
</Icons>
</UI>
</DispatchInfo>
</Extension>
</DispatchInfoList>
</ExtensionManifest>
`
}

View File

@@ -0,0 +1,61 @@
import { ICepConfig } from "./plugins";
const config: ICepConfig = {
"name": "cep-super-edition",
"id": "com.cep-super-edition",
"version": "0.0.1",
"extensionVersion": "6.1.0",
"requiredRuntimeVersion": "8.0",
"type": "Panel",
"parameters": [
"--enable-nodejs"
],
"panels": [
{
"name": "超级套版",
"displayName": "超级套版",
"main": "./index.html",
"width": 280,
"height": 600,
"minWidth": 280,
"minHeight": 600,
"maxWidth": 600,
"maxHeight": 4080
}
],
"hosts": [
{
"name": "AEFT",
"version": "[0.0,99.9]"
},
{
"name": "PPRO",
"version": "[0.0,99.9]"
},
{
"name": "ILST",
"version": "[0.0,99.9]"
},
{
"name": "PHXS",
"version": "[0.0,99.9]"
},
{
"name": "FLPR",
"version": "[0.0,99.9]"
}
],
"build": {
"jsxBin": false,
"country": "CN",
"province": "GD",
"org": "你的公司名称",
"password": "",
"tsa": ""
},
"zxp": {
"jsxBin": false
}
}
export default config;

View File

@@ -0,0 +1,239 @@
/**
* 构建客户端启动器Launcher
*
* 这个脚本只生成一个简单的 CEP 插件:
* - index.html跳转到服务器
* - manifest.xmlCEP 配置)
* - 图标等资源
*
* 用法npx ts-node scripts/buildLauncher.ts
*/
import * as fs from 'fs';
import * as path from 'path';
// ========== 配置 ==========
const CONFIG = {
// 服务器地址(客户打开插件后跳转到这里)
serverURL: 'https://aidg168.uk/app/#/login',
// CEP 插件信息
name: 'Designer',
id: 'com.designer.launcher',
version: '1.0.0',
displayName: '超级套版',
// 面板大小
panel: {
width: 450,
height: 600,
minWidth: 400,
minHeight: 500,
},
// 支持的 Adobe 软件
hosts: [
{ name: 'PHXS', version: '[0.0,99.9]' }, // Photoshop
{ name: 'ILST', version: '[0.0,99.9]' }, // Illustrator
{ name: 'AEFT', version: '[0.0,99.9]' }, // After Effects
{ name: 'PPRO', version: '[0.0,99.9]' }, // Premiere Pro
],
// 输出目录
outputDir: 'dist/Launcher',
};
// ========== 模板 ==========
// 跳转 HTML
const htmlTemplate = `<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>${CONFIG.displayName}</title>
<style>
body {
margin: 0;
padding: 20px;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: #1e1e1e;
color: #fff;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
box-sizing: border-box;
}
.loading {
text-align: center;
}
.spinner {
width: 40px;
height: 40px;
border: 3px solid #333;
border-top-color: #0078d4;
border-radius: 50%;
animation: spin 1s linear infinite;
margin: 0 auto 20px;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
.message {
font-size: 14px;
opacity: 0.8;
}
.error {
color: #ff6b6b;
display: none;
}
</style>
</head>
<body>
<div class="loading">
<div class="spinner"></div>
<p class="message">正在连接服务器...</p>
<p class="error" id="error">连接失败,请检查网络</p>
</div>
<script>
// 跳转到服务器
const serverURL = '${CONFIG.serverURL}';
// 延迟跳转,让用户看到加载动画
setTimeout(function() {
window.location.href = serverURL;
}, 500);
// 超时检测
setTimeout(function() {
document.getElementById('error').style.display = 'block';
}, 10000);
</script>
</body>
</html>`;
// manifest.xml
const manifestTemplate = `<?xml version="1.0" encoding="UTF-8"?>
<ExtensionManifest Version="6.0" ExtensionBundleId="${CONFIG.id}" ExtensionBundleVersion="${CONFIG.version}"
ExtensionBundleName="${CONFIG.name}" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ExtensionList>
<Extension Id="${CONFIG.id}.panel" Version="${CONFIG.version}" />
</ExtensionList>
<ExecutionEnvironment>
<HostList>
${CONFIG.hosts.map(h => `<Host Name="${h.name}" Version="${h.version}" />`).join('\n ')}
</HostList>
<LocaleList>
<Locale Code="All" />
</LocaleList>
<RequiredRuntimeList>
<RequiredRuntime Name="CSXS" Version="6.0" />
</RequiredRuntimeList>
</ExecutionEnvironment>
<DispatchInfoList>
<Extension Id="${CONFIG.id}.panel">
<DispatchInfo>
<Resources>
<MainPath>./index.html</MainPath>
<CEFCommandLine>
<Parameter>--enable-nodejs</Parameter>
<Parameter>--mixed-context</Parameter>
</CEFCommandLine>
</Resources>
<Lifecycle>
<AutoVisible>true</AutoVisible>
</Lifecycle>
<UI>
<Type>Panel</Type>
<Menu>${CONFIG.displayName}</Menu>
<Geometry>
<Size>
<Width>${CONFIG.panel.width}</Width>
<Height>${CONFIG.panel.height}</Height>
</Size>
<MinSize>
<Width>${CONFIG.panel.minWidth}</Width>
<Height>${CONFIG.panel.minHeight}</Height>
</MinSize>
</Geometry>
<Icons>
<Icon Type="Normal">./img/dark.png</Icon>
<Icon Type="RollOver">./img/highlight.png</Icon>
<Icon Type="DarkNormal">./img/dark.png</Icon>
<Icon Type="DarkRollOver">./img/highlight.png</Icon>
</Icons>
</UI>
</DispatchInfo>
</Extension>
</DispatchInfoList>
</ExtensionManifest>`;
// ========== 构建函数 ==========
function copyFolder(src: string, dest: string) {
if (!fs.existsSync(dest)) {
fs.mkdirSync(dest, { recursive: true });
}
const files = fs.readdirSync(src);
for (const file of files) {
const srcPath = path.join(src, file);
const destPath = path.join(dest, file);
if (fs.statSync(srcPath).isDirectory()) {
copyFolder(srcPath, destPath);
} else {
fs.copyFileSync(srcPath, destPath);
}
}
}
function build() {
console.log('🚀 构建客户端启动器...\n');
const outputDir = path.resolve(__dirname, '..', CONFIG.outputDir);
// 1. 清理输出目录
if (fs.existsSync(outputDir)) {
fs.rmSync(outputDir, { recursive: true });
}
fs.mkdirSync(outputDir, { recursive: true });
console.log('✓ 创建输出目录:', outputDir);
// 2. 创建 CSXS 目录
const csxsDir = path.join(outputDir, 'CSXS');
fs.mkdirSync(csxsDir, { recursive: true });
// 3. 写入 index.html
fs.writeFileSync(path.join(outputDir, 'index.html'), htmlTemplate);
console.log('✓ 生成 index.html');
// 4. 写入 manifest.xml
fs.writeFileSync(path.join(csxsDir, 'manifest.xml'), manifestTemplate);
console.log('✓ 生成 CSXS/manifest.xml');
// 5. 复制图标
const imgSrc = path.resolve(__dirname, '../plugins/jsx/template/cep/img');
const imgDest = path.join(outputDir, 'img');
if (fs.existsSync(imgSrc)) {
copyFolder(imgSrc, imgDest);
console.log('✓ 复制图标');
}
console.log('\n========================================');
console.log('✅ 构建完成!');
console.log('========================================');
console.log(`📁 输出目录: ${outputDir}`);
console.log(`🔗 跳转地址: ${CONFIG.serverURL}`);
console.log('\n下一步');
console.log('1. 使用 ZXPSignCmd 签名打包成 .zxp');
console.log('2. 或直接复制到 Adobe CEP 扩展目录测试');
}
// 执行
build();

View File

@@ -0,0 +1,64 @@
/**
* 超级简单的测试 - 验证最基础的 evalScript
*/
import { cep } from "@/utils/cep";
/**
* 测试1最简单的计算
*/
export async function testSimpleCalc() {
try {
const result = await cep.evalScript("1 + 2 + 3");
console.log('简单计算结果:', result);
return { success: true, result };
} catch (error) {
console.error('简单计算失败:', error);
return { success: false, error: String(error) };
}
}
/**
* 测试2获取应用名称不依赖任何工具库
*/
export async function testGetAppName() {
try {
const result = await cep.evalScript("app.name");
console.log('应用名称:', result);
return { success: true, appName: result };
} catch (error) {
console.error('获取应用名称失败:', error);
return { success: false, error: String(error) };
}
}
/**
* 测试3创建图层最简单版本不依赖工具库
*/
export async function testCreateLayerDirect() {
const jsx = `
(function() {
try {
if (app.documents.length === 0) {
return "no_document";
}
var doc = app.activeDocument;
var layer = doc.artLayers.add();
layer.name = "TestLayer";
return "success:" + layer.name;
} catch (e) {
return "error:" + e.toString();
}
})()
`;
try {
const result = await cep.evalScript(jsx);
console.log('创建图层结果:', result);
return { success: true, result };
} catch (error) {
console.error('创建图层失败:', error);
return { success: false, error: String(error) };
}
}

View File

@@ -0,0 +1,69 @@
import sys
import os
# Add current directory to sys.path
sys.path.append(os.getcwd())
from app.db import SessionLocal
from app.services.auth_service import auth_service
from app.schemas.auth import UserRegister
from app.core.security import get_password_hash
from app.models.user import User
def create_user(username, password, email=None):
db = SessionLocal()
try:
# Check if user exists
existing = db.query(User).filter(User.username == username).first()
if existing:
print(f"❌ 用户名 '{username}' 已存在")
return
# Prepare registration data
# We bypass the code verification by not providing code,
# but we set email if provided.
# However, auth_service.register sets is_verified=False by default if code is missing.
# We might want to manually set is_verified=True after registration for convenience.
register_data = UserRegister(
username=username,
password=password,
confirm_password=password,
email=email,
device_id="local_script"
)
# Call register service
try:
token = auth_service.register(db, register_data)
print(f"✅ 用户 '{username}' 注册成功!")
# Manually verify the user for local convenience
user = db.query(User).filter(User.username == username).first()
if user:
user.is_verified = True
user.permissions = "admin" # Grant admin permissions for local test user
db.commit()
print(f"✅ 已自动验证邮箱并赋予 admin 权限")
except Exception as e:
print(f"❌ 注册失败: {e}")
finally:
db.close()
if __name__ == "__main__":
if len(sys.path) < 2:
print("Usage: python create_user.py [username] [password]")
username = "admin"
password = "password123"
email = "admin@example.com"
if len(sys.argv) > 1:
username = sys.argv[1]
if len(sys.argv) > 2:
password = sys.argv[2]
print(f"正在创建用户: {username} ...")
create_user(username, password, email)

View File

@@ -0,0 +1,120 @@
# -*- coding: utf-8 -*-
"""
数据库初始化脚本
功能:
1. 检查数据库连接
2. 创建所有定义的表(如果不存在)
3. 检查现有表的字段,如果缺失则自动添加
"""
import os
import sys
import logging
from sqlalchemy import create_engine, inspect, text
from app.core.config import settings
from app.db import Base
# 导入所有模型以确保它们被注册到 Base.metadata
from app.models import user, group, business, session
# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def get_engine():
"""获取数据库引擎"""
# 优先使用环境变量中的配置,如果没有则构建
db_url = settings.DATABASE_URL
if not db_url:
host = os.getenv('DB_HOST', 'localhost')
port = os.getenv('DB_PORT', '3306')
user = os.getenv('DB_USER', 'root')
password = os.getenv('DB_PASSWORD', '')
db_name = os.getenv('DB_NAME', 'designer_db')
db_url = f"mysql+pymysql://{user}:{password}@{host}:{port}/{db_name}"
return create_engine(db_url)
def map_python_type_to_sql(col_type):
"""将 SQLAlchemy 类型映射为 MySQL 类型"""
type_str = str(col_type).lower()
if 'varchar' in type_str:
return type_str
if 'string' in type_str:
length = getattr(col_type, 'length', 255)
return f"varchar({length})"
if 'integer' in type_str or 'int' in type_str:
return "int"
if 'boolean' in type_str:
return "tinyint(1)"
if 'datetime' in type_str:
return "datetime"
if 'date' in type_str:
return "date"
if 'float' in type_str:
return "float"
if 'text' in type_str:
return "text"
return "varchar(255)" # 默认
def init_db():
logger.info("🔄 开始数据库初始化检查...")
try:
engine = get_engine()
inspector = inspect(engine)
# 1. 创建缺失的表
logger.info("📊 检查表结构...")
Base.metadata.create_all(bind=engine)
logger.info("✅ 基础表结构检查完成")
# 2. 检查并补充缺失的列
logger.info("🔍 检查缺失字段...")
existing_tables = inspector.get_table_names()
with engine.connect() as conn:
for table_name, table in Base.metadata.tables.items():
if table_name not in existing_tables:
continue
# 获取数据库中现有的列
existing_columns = [col['name'] for col in inspector.get_columns(table_name)]
# 检查模型定义的列
for column in table.columns:
if column.name not in existing_columns:
logger.info(f" 发现缺失字段: {table_name}.{column.name}")
# 构建 ALTER TABLE 语句
col_type = map_python_type_to_sql(column.type)
default_val = ""
# 处理默认值 (简化处理,只处理常见类型)
if column.default:
arg = column.default.arg
if isinstance(arg, (int, float, bool)):
if isinstance(arg, bool):
arg = 1 if arg else 0
default_val = f" DEFAULT {arg}"
elif isinstance(arg, str):
default_val = f" DEFAULT '{arg}'"
nullable = "NULL" if column.nullable else "NOT NULL"
if column.nullable and not default_val:
default_val = " DEFAULT NULL"
sql = f"ALTER TABLE {table_name} ADD COLUMN {column.name} {col_type} {nullable}{default_val};"
logger.info(f" 🚀 执行: {sql}")
conn.execute(text(sql))
conn.commit()
logger.info("✅ 数据库同步完成!")
except Exception as e:
logger.error(f"❌ 数据库初始化失败: {e}")
# 不抛出异常,以免阻断容器启动(如果是网络波动等临时问题)
# 但在生产环境中可能需要抛出
if __name__ == "__main__":
init_db()

View File

@@ -0,0 +1,170 @@
-- ==========================================
-- Database Initialization Script
-- Generated at: 2025-12-22 17:54:23.463367
-- ==========================================
-- 1. Select Database and Cleanup Tables
USE designer_db;
SET FOREIGN_KEY_CHECKS = 0;
DROP TABLE IF EXISTS check_in_config;
DROP TABLE IF EXISTS check_in_records;
DROP TABLE IF EXISTS features_config;
DROP TABLE IF EXISTS plugin_groups;
DROP TABLE IF EXISTS points_history;
DROP TABLE IF EXISTS vip_config;
DROP TABLE IF EXISTS users;
DROP TABLE IF EXISTS user_sessions;
SET FOREIGN_KEY_CHECKS = 1;
-- 2. Create Tables
CREATE TABLE check_in_config (
id INTEGER NOT NULL AUTO_INCREMENT,
consecutive_days INTEGER NOT NULL,
base_points INTEGER NOT NULL,
bonus_points INTEGER NOT NULL,
total_points INTEGER NOT NULL,
enabled BOOL,
created_at DATETIME DEFAULT now(),
updated_at DATETIME,
PRIMARY KEY (id),
UNIQUE (consecutive_days)
);
CREATE TABLE check_in_records (
id INTEGER NOT NULL AUTO_INCREMENT,
user_id INTEGER NOT NULL,
username VARCHAR(50) NOT NULL,
check_in_date DATE NOT NULL,
points_earned INTEGER NOT NULL,
consecutive_days INTEGER NOT NULL,
vip_multiplier FLOAT,
created_at DATETIME DEFAULT now(),
PRIMARY KEY (id)
);
CREATE TABLE features_config (
id INTEGER NOT NULL AUTO_INCREMENT,
feature_key VARCHAR(50) NOT NULL,
feature_name VARCHAR(100) NOT NULL,
category VARCHAR(50),
points_cost INTEGER,
vip_points_cost INTEGER,
svip_points_cost INTEGER,
enabled BOOL,
description TEXT,
created_at DATETIME DEFAULT now(),
updated_at DATETIME,
PRIMARY KEY (id)
);
CREATE TABLE plugin_groups (
id INTEGER NOT NULL AUTO_INCREMENT,
name VARCHAR(64) NOT NULL,
current_version_file VARCHAR(255),
comment TEXT,
PRIMARY KEY (id)
);
CREATE TABLE points_history (
id INTEGER NOT NULL AUTO_INCREMENT,
user_id INTEGER NOT NULL,
username VARCHAR(50) NOT NULL,
type VARCHAR(20) NOT NULL,
amount INTEGER NOT NULL,
balance INTEGER NOT NULL,
description VARCHAR(255),
created_at DATETIME DEFAULT now(),
PRIMARY KEY (id)
);
CREATE TABLE vip_config (
id INTEGER NOT NULL AUTO_INCREMENT,
vip_type VARCHAR(20) NOT NULL,
name VARCHAR(50) NOT NULL,
price FLOAT NOT NULL,
daily_quota INTEGER NOT NULL,
points_multiplier FLOAT,
enabled BOOL,
description TEXT,
created_at DATETIME DEFAULT now(),
updated_at DATETIME,
PRIMARY KEY (id),
UNIQUE (vip_type)
);
CREATE TABLE users (
id INTEGER NOT NULL AUTO_INCREMENT,
username VARCHAR(64) NOT NULL,
hashed_password VARCHAR(128) NOT NULL,
created_at DATETIME NOT NULL DEFAULT now(),
group_id INTEGER,
permissions TEXT,
expire_date DATETIME,
email VARCHAR(255),
is_verified BOOL,
verification_code VARCHAR(6),
reset_token VARCHAR(128),
reset_token_expire DATETIME,
nickname VARCHAR(50),
avatar VARCHAR(500),
points INTEGER,
level INTEGER,
vip_type VARCHAR(20),
vip_expire DATETIME,
vip_daily_quota INTEGER,
vip_quota_reset_date DATE,
total_check_in_days INTEGER,
consecutive_check_in INTEGER,
last_check_in_date DATE,
PRIMARY KEY (id),
FOREIGN KEY(group_id) REFERENCES plugin_groups (id)
);
CREATE TABLE user_sessions (
id INTEGER NOT NULL AUTO_INCREMENT,
user_id INTEGER NOT NULL,
device_id VARCHAR(128) NOT NULL,
active BOOL NOT NULL,
expires_at DATETIME,
created_at DATETIME NOT NULL DEFAULT now(),
login_at DATETIME,
logout_at DATETIME,
duration_seconds INTEGER,
last_seen_at DATETIME,
PRIMARY KEY (id),
FOREIGN KEY(user_id) REFERENCES users (id)
);
-- 3. Insert Initial Data
-- Default User Group
INSERT INTO plugin_groups (name, comment) VALUES ('default', 'Default User Group');
-- VIP Config
INSERT INTO vip_config (vip_type, name, price, daily_quota, points_multiplier) VALUES ('vip', 'VIP会员', 30.0, 20, 1.5);
INSERT INTO vip_config (vip_type, name, price, daily_quota, points_multiplier) VALUES ('svip', 'SVIP会员', 88.0, -1, 2.0);
-- Check-in Config
INSERT INTO checkin_config (consecutive_days, base_points, bonus_points, total_points) VALUES (1, 10, 0, 10);
INSERT INTO checkin_config (consecutive_days, base_points, bonus_points, total_points) VALUES (3, 10, 5, 15);
INSERT INTO checkin_config (consecutive_days, base_points, bonus_points, total_points) VALUES (7, 10, 20, 30);
-- Feature Config
INSERT INTO feature_configs (feature_key, feature_name, points_cost, category) VALUES ('ai_remove_bg', '智能抠图', 10, 'ai');
-- 4. Create Admin User (admin / password123)
INSERT INTO users (
username, hashed_password, email, is_verified, permissions,
group_id, nickname, level, vip_type, vip_expire,
created_at, points, total_check_in_days, consecutive_check_in, vip_daily_quota
) VALUES (
'admin',
'$2b$12$UsFjs3Jwn5BG7u/RJ1efNuTF4zIsjT.pSm1mQEBXGWKR.3Kakhpmq',
'admin@example.com',
1,
'admin,vip,svip',
(SELECT id FROM plugin_groups WHERE name = 'default' LIMIT 1),
'Administrator',
999,
'svip',
'2099-12-31 23:59:59',
NOW(),
0, 0, 0, 0
);

View File

@@ -0,0 +1,292 @@
# -*- coding: utf-8 -*-
"""
完整数据库初始化脚本 (Local Execution)
功能:
1. 重建数据库DROP & CREATE DATABASE
2. 创建所有表结构
3. 创建默认数据用户组、VIP配置、签到配置、功能配置
4. 创建默认管理员账户 (admin/password123)
注意:此脚本设计为在本地或 Docker 容器内运行,直接连接 MySQL。
它会读取环境变量或使用默认配置。
"""
import logging
import os
import sys
import argparse
from datetime import datetime
from sqlalchemy.schema import CreateTable
# 确保可以将当前目录添加到 sys.path
sys.path.append(os.getcwd())
from sqlalchemy import create_engine, text
from sqlalchemy.orm import sessionmaker
from sqlalchemy.engine.url import make_url
# 尝试导入应用模块
try:
from app.core.config import settings
from app.db import Base
from app.models import user, group, business, session
from app.models.user import User
from app.models.group import PluginGroup
from app.models.business import FeatureConfig, VipConfig, CheckInConfig
from app.core.security import get_password_hash
except ImportError:
print("❌ 无法导入应用模块,请确保在 Server 目录下运行此脚本")
print("示例: python scripts/init_full_db.py")
sys.exit(1)
# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
def generate_sql_file():
"""生成完整的初始化 SQL 文件"""
logger.info("📝 正在生成 SQL 文件 (init_db.sql) ...")
# 获取数据库引擎 (用于编译 SQL)
# 我们使用一个 mock engine因为我们只想要 SQL 语句
engine = create_engine("mysql+pymysql://", strategy="mock", executor=lambda sql, *args, **kwargs: print(sql.compile(dialect=engine.dialect)))
# 真正的 engine 用于 dialect 编译
compile_engine = create_engine("mysql+pymysql://")
sql_content = []
# 1. 准备数据库
sql_content.append("-- ==========================================")
sql_content.append("-- Database Initialization Script")
sql_content.append(f"-- Generated at: {datetime.now()}")
sql_content.append("-- ==========================================\n")
# 既然 DROP DATABASE 被禁用,我们切换到目标数据库,并尝试删除所有表
sql_content.append("-- 1. Select Database and Cleanup Tables")
sql_content.append("USE designer_db;\n")
# 获取所有表名并生成 DROP TABLE 语句
# 注意:为了处理外键约束,我们先禁用外键检查
sql_content.append("SET FOREIGN_KEY_CHECKS = 0;")
for table in Base.metadata.sorted_tables:
sql_content.append(f"DROP TABLE IF EXISTS {table.name};")
sql_content.append("SET FOREIGN_KEY_CHECKS = 1;\n")
# 2. 创建表结构
sql_content.append("-- 2. Create Tables")
for table in Base.metadata.sorted_tables:
create_table_sql = CreateTable(table).compile(compile_engine)
sql_content.append(str(create_table_sql).strip() + ";\n")
# 3. 插入初始数据
sql_content.append("-- 3. Insert Initial Data")
# 用户组
sql_content.append("-- Default User Group")
sql_content.append("INSERT INTO plugin_groups (name, comment) VALUES ('default', 'Default User Group');")
# VIP 配置
sql_content.append("-- VIP Config")
sql_content.append("INSERT INTO vip_config (vip_type, name, price, daily_quota, points_multiplier) VALUES ('vip', 'VIP会员', 30.0, 20, 1.5);")
sql_content.append("INSERT INTO vip_config (vip_type, name, price, daily_quota, points_multiplier) VALUES ('svip', 'SVIP会员', 88.0, -1, 2.0);")
# 签到配置
sql_content.append("-- Check-in Config")
sql_content.append("INSERT INTO checkin_config (consecutive_days, base_points, bonus_points, total_points) VALUES (1, 10, 0, 10);")
sql_content.append("INSERT INTO checkin_config (consecutive_days, base_points, bonus_points, total_points) VALUES (3, 10, 5, 15);")
sql_content.append("INSERT INTO checkin_config (consecutive_days, base_points, bonus_points, total_points) VALUES (7, 10, 20, 30);")
# 功能配置
sql_content.append("-- Feature Config")
sql_content.append("INSERT INTO feature_configs (feature_key, feature_name, points_cost, category) VALUES ('ai_remove_bg', '智能抠图', 10, 'ai');")
# 4. 创建管理员
sql_content.append("-- 4. Create Admin User (admin / password123)")
# 计算密码哈希 (这里直接计算一次固定的,避免每次运行不一样)
# password123 的 bcrypt hash (示例)
# 为了准确,我们还是用 python 算一下
admin_hash = get_password_hash("password123")
# 获取 default group id (假设是 1因为刚刚插入且是第一个)
sql_content.append(f"""
INSERT INTO users (
username, hashed_password, email, is_verified, permissions,
group_id, nickname, level, vip_type, vip_expire,
created_at, points, total_check_in_days, consecutive_check_in, vip_daily_quota
) VALUES (
'admin',
'{admin_hash}',
'admin@example.com',
1,
'admin,vip,svip',
(SELECT id FROM plugin_groups WHERE name = 'default' LIMIT 1),
'Administrator',
999,
'svip',
'2099-12-31 23:59:59',
NOW(),
0, 0, 0, 0
);
""")
# 写入文件
output_file = "init_db.sql"
with open(output_file, "w", encoding="utf-8") as f:
f.write("\n".join(sql_content))
logger.info(f"✅ SQL 文件已生成: {output_file}")
print(f"\nSQL 文件已生成: {os.path.abspath(output_file)}")
print("您可以直接在 phpMyAdmin 中导入此文件来初始化数据库。")
def get_db_url():
"""获取数据库连接 URL"""
# 优先使用 settings 中的配置
# db_url = settings.DATABASE_URL
# 用户指定的远程数据库
# Host: 103.97.201.136
# Port: 3388 (映射到了容器内的 3306)
# User: designer_user
# Pass: DesignerPass123!
db_url = "mysql+pymysql://designer_user:DesignerPass123!@103.97.201.136:3388/designer_db"
# 如果 settings 是默认的 sqlite尝试构建 mysql 连接(用于本地开发时的强制覆盖)
# if db_url.startswith("sqlite"):
# # 默认开发环境 Docker MySQL 配置
# db_url = "mysql+pymysql://designer_user:DesignerPass123!@localhost:3306/designer_db"
# logger.info(f"⚠️ 检测到 SQLite 配置,切换为默认 MySQL 配置: {db_url}")
logger.info(f"🔌 使用数据库配置: {db_url}")
return db_url
def recreate_database(engine, db_name):
"""重建数据库"""
logger.info(f"🗑️ 正在重建数据库: {db_name}...")
# 获取 root 连接(连接到 mysql 系统库或不指定库)
url = make_url(engine.url)
root_url = url.set(database='mysql')
# 使用 AUTOCOMMIT 隔离级别
root_engine = create_engine(root_url, isolation_level="AUTOCOMMIT")
with root_engine.connect() as conn:
conn.execute(text(f"DROP DATABASE IF EXISTS {db_name}"))
conn.execute(text(f"CREATE DATABASE {db_name} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"))
logger.info(f"✅ 数据库 {db_name} 重建完成")
def seed_initial_data(session):
"""填充初始数据"""
logger.info("🌱 正在填充初始数据...")
# 1. 默认用户组
if session.query(PluginGroup).filter(PluginGroup.name == "default").count() == 0:
logger.info(" - 创建默认用户组 'default'")
default_group = PluginGroup(name="default", comment="Default User Group")
session.add(default_group)
# 2. VIP 配置
if session.query(VipConfig).count() == 0:
logger.info(" - 创建 VIP 配置")
session.add(VipConfig(vip_type="vip", name="VIP会员", price=30.0, daily_quota=20, points_multiplier=1.5))
session.add(VipConfig(vip_type="svip", name="SVIP会员", price=88.0, daily_quota=-1, points_multiplier=2.0))
# 3. 签到配置
if session.query(CheckInConfig).count() == 0:
logger.info(" - 创建签到配置")
session.add(CheckInConfig(consecutive_days=1, base_points=10, bonus_points=0, total_points=10))
session.add(CheckInConfig(consecutive_days=3, base_points=10, bonus_points=5, total_points=15))
session.add(CheckInConfig(consecutive_days=7, base_points=10, bonus_points=20, total_points=30))
# 4. 功能配置
if session.query(FeatureConfig).count() == 0:
logger.info(" - 创建功能配置")
session.add(FeatureConfig(feature_key="ai_remove_bg", feature_name="智能抠图", points_cost=10, category="ai"))
session.commit()
logger.info("✅ 初始数据填充完成")
def create_admin_user(session):
"""创建管理员用户"""
username = "admin"
password = "123456"
email = "admin@example.com"
existing = session.query(User).filter(User.username == username).first()
if existing:
logger.info(f" 管理员用户 '{username}' 已存在,跳过创建")
return
logger.info(f"👤 正在创建管理员用户: {username} ...")
# 获取默认组
default_group = session.query(PluginGroup).filter(PluginGroup.name == "default").first()
group_id = default_group.id if default_group else None
new_user = User(
username=username,
hashed_password=get_password_hash(password),
email=email,
is_verified=True,
permissions="admin,vip,svip", # 赋予所有权限
group_id=group_id,
nickname="Administrator",
level=999,
vip_type="svip",
vip_expire=datetime(2099, 12, 31)
)
session.add(new_user)
session.commit()
logger.info(f"✅ 管理员用户创建成功!(User: {username}, Pass: {password})")
def main():
parser = argparse.ArgumentParser(description='Initialize DesignerCEP Database')
parser.add_argument('--generate-sql', action='store_true', help='Generate init_db.sql file only')
args = parser.parse_args()
if args.generate_sql:
generate_sql_file()
return
logger.info("🚀 开始全量数据库初始化流程")
try:
db_url = get_db_url()
engine = create_engine(db_url)
# 1. 重建数据库
# 注意:这会删除现有数据!
db_name = make_url(db_url).database
recreate_database(engine, db_name)
# 重新连接到新创建的数据库
target_engine = create_engine(db_url)
# 2. 创建表结构
logger.info("🏗️ 正在创建表结构...")
Base.metadata.create_all(bind=target_engine)
logger.info("✅ 表结构创建完成")
# 3. 数据填充
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=target_engine)
session = SessionLocal()
try:
seed_initial_data(session)
create_admin_user(session)
finally:
session.close()
logger.info("✨✨✨ 数据库初始化全部完成! ✨✨✨")
except Exception as e:
logger.error(f"❌ 初始化失败: {str(e)}")
sys.exit(1)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,7 @@
@echo off
rem D:\Python37\Scripts\pyinstaller.exe -w -i ./newapp.ico run.py
pyinstaller -w -i ./newapp.ico run.py
pause

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

View File

@@ -0,0 +1,396 @@
import os
import shutil
import sys
import tempfile
import time
import wmi
import psutil
import threading
import qtpy, platform
import winreg
from qtpy.QtCore import Qt, QMetaObject, Signal, Slot, QEvent
from qtpy.QtWidgets import QWidget, QVBoxLayout, QInputDialog, QHBoxLayout, QToolButton, QLabel, QSizePolicy, QSplashScreen
from PyQt5.QtGui import QIcon, QPixmap
import re
import hashlib
import configparser
from win32com.client import Dispatch
import ezdxf
import zipfile
import PyQt5
from PyQt5.QtWidgets import QApplication, QDialog, QMainWindow, QVBoxLayout, QWidget, QTabWidget, QPushButton, QLabel, QVBoxLayout, QWidget, QHBoxLayout, QFrame, QMessageBox
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import Qt
import qdarktheme
import sys
import subprocess
import re
import hashlib
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QPushButton, QGroupBox, \
QSpacerItem, QSizePolicy, QMessageBox
import pymysql
import requests
BASE_URL = "http://43.134.82.18/psmark"
#BASE_URL = "http://127.0.0.1:5001"
tempdir = ""
def exception_hook(exctype, value, traceback):
# Handle the uncaught exception
# 处理未捕获的异常
QMessageBox.warning(None, "错误", f"发生了未知的异常:{value}")
class LoginDialog(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("PSMARK登录界面")
self.setWindowIcon(QIcon("icons/newapp.ico")) # 设置窗口小图标,替换为您的图标文件路径
self.resize(300, 200)
主布局 = QVBoxLayout()
group1 = QGroupBox("登录验证")
group1_layout = QVBoxLayout()
group2 = QHBoxLayout()
label1 = QLabel("用户名")
self.edit1 = QLineEdit()
self.edit1.setFixedWidth(200)
spacer1 = QSpacerItem(40, 10, QSizePolicy.Expanding, QSizePolicy.Minimum)
group2.addWidget(label1)
group2.addItem(spacer1)
group2.addWidget(self.edit1)
group3 = QHBoxLayout()
label2 = QLabel("密码")
self.edit2 = QLineEdit()
self.edit2.setFixedWidth(200)
self.edit2.setEchoMode(QLineEdit.Password) # 设置密码输入框为密文
spacer2 = QSpacerItem(40, 10, QSizePolicy.Expanding, QSizePolicy.Minimum)
group3.addWidget(label2)
group3.addItem(spacer2)
group3.addWidget(self.edit2)
group4 = QHBoxLayout()
button1 = QPushButton("登录")
button2 = QPushButton("注册")
group4.addWidget(button1)
group4.addWidget(button2)
group1_layout.addLayout(group2)
group1_layout.addLayout(group3)
group1_layout.addLayout(group4)
group1.setLayout(group1_layout)
主布局.addWidget(group1)
group5 = QHBoxLayout()
label3 = QLabel("机器码")
self.edit3 = QLineEdit()
self.edit3.setFixedWidth(200)
self.edit3.setReadOnly(True)
self.edit3.setFocusPolicy(Qt.NoFocus)
# 获取主板序列号并提取数字部分
'''try:
result = subprocess.run(['wmic', 'baseboard', 'get', 'serialnumber'], stdout=subprocess.PIPE,
stderr=subprocess.PIPE, text=True)
motherboard_serial = result.stdout.strip()
# 使用正则表达式提取数字
motherboard_serial = re.sub(r'\D', '', motherboard_serial)
# 使用SHA-256加密特征码
feature_code = hashlib.sha256(motherboard_serial.encode()).hexdigest()
# 去掉特征码中的英文字符
feature_code = re.sub(r'[a-zA-Z]', '', feature_code)
except Exception as e:
feature_code = "Error: " + str(e)'''
# 计算序列号
try:
feature_code = self.get_computer_code()
count = ord(feature_code[0]) + ord(feature_code[1])
for _ in range(count):
feature_code = hashlib.md5(feature_code.encode()).hexdigest().upper()
except Exception as e:
feature_code = "Error: " + str(e)
self.edit3.setText(feature_code) # 将加密后的特征码设置为 "特征码" 输入框的文本
self.rem_user()
spacer3 = QSpacerItem(10, 10, QSizePolicy.Fixed, QSizePolicy.Minimum)
group5.addWidget(label3)
group5.addItem(spacer3)
group5.addWidget(self.edit3)
主布局.addLayout(group5)
self.setLayout(主布局)
# 链接登录的点击事件
button1.clicked.connect(self.slot_login)
# 连接注册按钮的点击事件
button2.clicked.connect(self.register)
def get_computer_code(self):
computer_code = ''
c = wmi.WMI()
for cpu in c.Win32_Processor():
computer_code += cpu.ProcessorId.strip()
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\SQMClient", 0, winreg.KEY_READ | winreg.KEY_WOW64_64KEY)
# 读取设备ID
computer_code += winreg.QueryValueEx(key, "MachineId")[0].strip()
# 关闭注册表
winreg.CloseKey(key)
computer_code += str(subprocess.check_output('wmic csproduct get uuid').split(b'\n')[1].strip())
return computer_code
def register(self):
dialog = RegisterDialog()
if dialog.exec() != QDialog.Accepted:
return
r = requests.post(BASE_URL + f"/register", data={
"username":dialog.get用户名(),
"password":dialog.get密码(),
"code":self.edit3.text(),
"adminpassword":"qwe123456",
"truename":dialog.get姓名(),
"phone":dialog.get手机号(),
"company":dialog.get公司名(),
"address":dialog.get地址(),
})
if r.text == "success":
QMessageBox.information(self, "成功", "注册成功!")
elif r.text == 'exist':
QMessageBox.critical(self, "错误", "用户已存在!")
else:
QMessageBox.critical(self, "错误", f"注册失败!{r.text}")
#记住密码
def rem_user(self):
global tempdir
code = self.edit3.text()
r = requests.post(BASE_URL + f"/query?code={code}")
with tempfile.TemporaryDirectory() as d:
dname = d
tempdir = dname + str(time.time())
os.makedirs(tempdir)
filepath = os.path.join(tempdir, "result.zip")
with open(filepath, 'wb') as f:
f.write(r.content)
with zipfile.ZipFile(filepath, 'r') as zip_ref:
zip_ref.extractall(tempdir)
with open(os.path.join(tempdir, "userinfo.txt"), 'r', encoding="utf-8") as f:
userinfo = f.read()
if userinfo == 'error':
return
self.edit1.setText(userinfo.split("\n")[0])
self.edit2.setText(userinfo.split("\n")[1])
def slot_login(self):
global tempdir
user_name = self.edit1.text()
user_password = self.edit2.text()
code = self.edit3.text()
# 判断缓存是否存在
with open(os.path.join(tempdir, "userinfo.txt"), 'r', encoding="utf-8") as f:
userinfo = f.read()
if not (userinfo.split("\n")[0] == user_name and userinfo.split("\n")[1] == user_password):
r = requests.post(BASE_URL + f"/query?code={code}&username={user_name}&password={user_password}")
with tempfile.TemporaryDirectory() as d:
dname = d
tempdir = dname + str(time.time())
os.makedirs(tempdir)
filepath = os.path.join(tempdir, "result.zip")
with open(filepath, 'wb') as f:
f.write(r.content)
with zipfile.ZipFile(filepath, 'r') as zip_ref:
zip_ref.extractall(tempdir)
with open(os.path.join(tempdir, "userinfo.txt"), 'r', encoding="utf-8") as f:
userinfo = f.read()
if userinfo == 'error':
QMessageBox.critical(self, "错误", "机器码或账号密码错误!")
return
with zipfile.ZipFile(os.path.join(tempdir, "data.zip"), 'r') as zip_ref:
zip_ref.extractall(tempdir)
#print(tempdir)
cwd = os.getcwd()
sys.path.insert(0, tempdir)
os.chdir(tempdir)
import piece_decorative
piece_decorative.config = configparser.ConfigParser()
os.chdir(cwd)
piece_decorative.config.read('config.ini', encoding='utf-8')
piece_decorative.PSname = piece_decorative.config.get('程序配置', 'PSname')
os.chdir(tempdir)
import newMark
#self.hide()
self.window = newMark.MainWindow()
self.window.show()
self.close()
#print("run")
#newMark.run()
def show_warning_message(self):
# 弹出警告消息框
QMessageBox.critical(self, "错误", "请联系管理员 17520145271")
# warning_message = QMessageBox()
# warning_message.setIcon(QMessageBox.Warning)
# warning_message.setWindowTitle("警告")
# warning_message.setText("请联系管理员 17520145271")
# warning_message.exec_()
from PyQt5.QtWidgets import QDialogButtonBox, QFormLayout
from PyQt5.QtGui import QIntValidator
import re
class RegisterDialog(QDialog):
'''注册对话框'''
def __init__(self):
super(RegisterDialog,self).__init__()
self.init_gui()
def init_gui(self):
#设置dialog窗口标题
self.setWindowTitle("注册")
# 设置界面尺寸大小
self.resize(500, 260)
self.用户名QLineEdit = QLineEdit()
self.密码QLineEdit = QLineEdit()
self.密码QLineEdit.setEchoMode(QLineEdit.Password)
self.确认密码QLineEdit = QLineEdit()
self.确认密码QLineEdit.setEchoMode(QLineEdit.Password)
self.姓名QLineEdit = QLineEdit()
self.手机号QLineEdit = QLineEdit()
#self.手机号QLineEdit.setValidator(QIntValidator())
self.公司名QLineEdit = QLineEdit()
self.地址QLineEdit = QLineEdit()
self.buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self)
self.buttons.accepted.connect(self.check)
self.buttons.rejected.connect(self.reject)
# 表单布局,当然也可以使用其它布局方式
layout = QFormLayout(self)
layout.addRow('用户名(用于登录):', self.用户名QLineEdit)
layout.addRow('密码(用于登录):', self.密码QLineEdit)
layout.addRow('确认密码:', self.确认密码QLineEdit)
layout.addRow('姓名:', self.姓名QLineEdit)
layout.addRow('手机号(+86):', self.手机号QLineEdit)
layout.addRow('公司名:', self.公司名QLineEdit)
layout.addRow('地址:', self.地址QLineEdit)
layout.addRow(self.buttons)
def get用户名(self):
return self.用户名QLineEdit.text().strip()
def get密码(self):
return self.密码QLineEdit.text().strip()
def get确认密码(self):
return self.确认密码QLineEdit.text().strip()
def get姓名(self):
return self.姓名QLineEdit.text().strip()
def get手机号(self):
return self.手机号QLineEdit.text().strip()
def get公司名(self):
return self.公司名QLineEdit.text().strip()
def get地址(self):
return self.地址QLineEdit.text().strip()
def check(self):
if self.get用户名() == '' or self.get密码() == '' or self.get姓名() == '' or self.get手机号() == '' or self.get公司名() == '' or self.get地址() == '':
QMessageBox.critical(self, "错误", "信息不完整!")
return
if self.get密码() != self.get确认密码():
QMessageBox.critical(self, "错误", "两次密码不一致!")
return
t = re.compile(r'[1-9][0-9]{10}')
s = re.search(t, self.get手机号())
if (not s) or (not self.get手机号().startswith('1')) or (len(self.get手机号()) != 11):
QMessageBox.critical(self, "错误", "手机号格式错误!")
return
self.accept()
def main():
app3 = QApplication(sys.argv)
sys.excepthook = exception_hook # 设置全局异常处理
splash = QSplashScreen()
splash.setPixmap(QPixmap('./splash.png'))
splash.show()
app3.processEvents()
qdarktheme.setup_theme(
custom_colors={
"[dark]": {
"background": "#4d4d4d",
"foreground": "#ffffff",
"primary": "#ffffff",
"border": "#717070",
}
}
)
login_dialog = LoginDialog()
login_dialog.show()
splash.finish(login_dialog) # 启动画面完成启动
# window = MainWindow()
# window.show()
r = app3.exec_()
time.sleep(1)
os.chdir("C:")
try:
if tempdir != "":
shutil.rmtree(tempdir, ignore_errors=True)
#print("temp dir remove ok:", tempdir)
except Exception as e:
print(e)
sys.exit(r)
if __name__ == '__main__':
main()

View File

@@ -0,0 +1,51 @@
# -*- mode: python ; coding: utf-8 -*-
block_cipher = None
a = Analysis(
['run.py'],
pathex=[],
binaries=[],
datas=[],
hiddenimports=[],
hookspath=[],
hooksconfig={},
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher,
noarchive=False,
)
pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)
exe = EXE(
pyz,
a.scripts,
[],
exclude_binaries=True,
name='run',
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
console=False,
disable_windowed_traceback=False,
argv_emulation=False,
target_arch=None,
codesign_identity=None,
entitlements_file=None,
icon=['newapp.ico'],
)
coll = COLLECT(
exe,
a.binaries,
a.zipfiles,
a.datas,
strip=False,
upx=True,
upx_exclude=[],
name='run',
)

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

View File

@@ -0,0 +1,4 @@
# -*- coding: utf-8 -*-
[程序配置]
PSname = Photoshop.Application.120

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,191 @@
dxf12_jscode = """
批量套数写入()
function 批量套数写入() {
app.preferences.rulerUnits = Units.CM;
var 主文档 = app.activeDocument;
var 主文档名称 = 主文档.name;
// 遍历当前打开的文档
for (var i = 0; i < app.documents.length; i++) {
var document = app.documents[i];
var documentName = document.name;
// 判断文档名称是否与主文档名称不相同
if (documentName !== 主文档名称) {
// 设置当前文档为活动文档
app.activeDocument = document;
var 匹配图层数组 = 遍历图层查找P1();
// 遍历匹配图层数组
for (var j = 0; j < 匹配图层数组.length; j++) {
var 当前匹配图层 = 匹配图层数组[j];
}
// 选中当前匹配图层
// 获取当前选区
var currentSelection = app.activeDocument.selection;
// 确保当前选区不为空且为矩形选区
if (currentSelection != null && currentSelection.hasOwnProperty('bounds')) {
// 进行缩放操作
app.activeDocument.activeLayer = 当前匹配图层;
// 载入选区
载入选区();
// 获取当前选区的坐标
var bounds = currentSelection.bounds;
// 获取当前选区的宽度和高度(以 cm 为单位)
var resolution = app.activeDocument.resolution;
var widthInCM = (bounds[2].as("cm") - bounds[0].as("cm"));
var heightInCM = (bounds[3].as("cm") - bounds[1].as("cm"));
var 当前P1图层宽高信息 = "宽度:" + widthInCM.toFixed(2) + "cm高度" + heightInCM.toFixed(2) + "cm";
// 获取当前裁片套数
var 搜索关键词 = "P1";
var 匹配的图层数量 = 获取匹配图层数量(搜索关键词);
var 当前裁片套数 = "一段" + 匹配的图层数量 + "";
// 创建新图层并设置名称
/// var 新图层 = 主文档.artLayers.add();
// var 新图层 = "当前文档宽度缩水" + 宽度值 + "高度缩水" + 高度值;
// 移动选区到新图层
// currentSelection.cut();
// app.activeDocument.paste();
// alert(当前裁片套数);
// alert( 当前P1图层宽高信息);
// 文件简介写入
文件简介写入(当前裁片套数, 当前P1图层宽高信息 );
// 这里删除了文件简介的写入将缩水值修改按钮
// 调整图像尺寸(宽度值, 高度值);
////这里取消了保存功能 为了防止运行的时候变卡
//activeDocument.save();
} else {
// alert("没有找到匹配的图层。");
}
}
}
app.activeDocument=主文档
// alert("写入信息成功","来自左威的提醒");
}
function 文件简介写入(当前裁片套数, 当前P1图层宽高信息) {
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("property"), stringIDToTypeID("fileInfo"));
r.putEnumerated(stringIDToTypeID("document"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
var d1 = new ActionDescriptor();
d1.putString(stringIDToTypeID("caption"), 当前裁片套数);
d1.putString(stringIDToTypeID("keywords"), 当前P1图层宽高信息);
d.putObject(stringIDToTypeID("to"), stringIDToTypeID("fileInfo"), d1);
executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
}
function 调整图像尺寸(宽度值, 高度值) {
var 动作描述 = new ActionDescriptor();
动作描述.putUnitDouble(stringIDToTypeID("width"), stringIDToTypeID("percentUnit"), 100 + 宽度值);
动作描述.putUnitDouble(stringIDToTypeID("height"), stringIDToTypeID("percentUnit"), 100 + 高度值);
动作描述.putEnumerated(charIDToTypeID("Intr"), stringIDToTypeID("interpolationType"), stringIDToTypeID("nearestNeighbor"));
executeAction(stringIDToTypeID("imageSize"), 动作描述, DialogModes.NO);
}
function 载入选区() //载入选区
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("channel"), stringIDToTypeID("selection"));
d.putReference(stringIDToTypeID("null"), r);
var r1 = new ActionReference();
r1.putEnumerated(stringIDToTypeID("channel"), stringIDToTypeID("channel"), stringIDToTypeID("transparencyEnum"));
d.putReference(stringIDToTypeID("to"), r1);
executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
}
function 遍历图层查找P1() {
var 匹配图层数组 = [];
var 文档 = app.activeDocument;
// 遍历所有图层
function 遍历所有图层(图层) {
if (图层.typename === "LayerSet") {
for (var i = 0; i < 图层.layers.length; i++) {
遍历所有图层(图层.layers[i]);
}
} else {
var 图层名分割数组 = 图层.name.split("-"); // 假设分割符是 "_"
if (图层名分割数组[0] === "P1") { // 精确匹配
匹配图层数组.push(图层);
}
}
}
// 开始遍历
for (var j = 0; j < 文档.layers.length; j++) {
遍历所有图层(文档.layers[j]);
}
return 匹配图层数组;
}
function 获取匹配图层数量(搜索关键词) {
var 匹配图层数量 = 0;
// 递归遍历图层及其子图层
function 遍历图层(图层) {
if (图层.typename === "LayerSet") {
for (var i = 0; i < 图层.layers.length; i++) {
遍历图层(图层.layers[i]);
}
} else {
// 进行模糊匹配和精确分割匹配
if (图层.name.indexOf(搜索关键词) !== -1 && 精确分割匹配图层(图层.name, 搜索关键词)) {
匹配图层数量++;
}
}
}
// 精确分割匹配图层名
function 精确分割匹配图层(图层名, 搜索词) {
var 图层名分割数组 = 图层名.split("-"); // 假设分割符是 "_"
return 图层名分割数组[0] === 搜索词;
}
var 当前文档 = app.activeDocument;
var 所有图层 = 当前文档.layers;
for (var i = 0; i < 所有图层.length; i++) {
遍历图层(所有图层[i]);
}
return 匹配图层数量;
}
"""

View File

@@ -0,0 +1,982 @@
dxf13_jscode = """
function 裁片射出宽高缩放() {
app.preferences.rulerUnits = Units.PIXELS
var 主文档 = app.activeDocument;
var 主文档名称 = 主文档.name;
// 遍历当前打开的文档
for (var i = 0; i < app.documents.length; i++) {
var document = app.documents[i];
var documentName = document.name;
// 判断文档名称是否与主文档名称不相同
if (documentName !== 主文档名称) {
app.activeDocument = document;
遍历图层();
}
}
function 遍历图层() {
var layerNames = []; // 用于存储图层名称的数组
var currentDocument = app.activeDocument;
for (var j = 0; j < currentDocument.layers.length; j++) {
var layer = currentDocument.layers[j];
var layerName = layer.name;
layerNames.push(layerName);
}
// 逐个处理图层
for (var k = 0; k < layerNames.length; k++) {
var 当前图层名称 = layerNames[k];
// $.writeln("图层名称:" + 当前图层名称);
// alert(当前图层名称);
var parts = 当前图层名称.split("-");
if (parts.length > 0) {
var 裁片名称 = parts[0];
app.activeDocument = 主文档;
$.writeln(裁片名称);
初始化模板裁片名称 = 当前图层名称.split("-");
初始化码数裁片名称 = 当前图层名称.split("_");
大货组名称 =初始化模板裁片名称[0]+("-大货裁片")
实际裁片名称 = 初始化模板裁片名称[0]+"-"+初始化码数裁片名称[2]
$.writeln(大货组名称);
$.writeln(实际裁片名称);
var 空白裁片模板 = app.activeDocument.layerSets.getByName(大货组名称).layers.getByName(实际裁片名称 );
app.activeDocument.activeLayer = 空白裁片模板;
载入选区()
var 边距 = 获取当前选区四边距();
var 当前选区高度=边距.bottom-边距.top
var 当前选区宽度=边距.right-边距.left
var 高度转毫米 = pixelsToMillimeters(当前选区高度);
var 宽度转毫米 = pixelsToMillimeters(当前选区宽度);
var 搜索词 = 裁片名称;
var 匹配图层数组 = 匹配图层名(搜索词);
// 显示匹配的图层列表
if (匹配图层数组.length > 0) {
var 图层列表文本 = "匹配的图层列表:";
for (var i = 0; i < 匹配图层数组.length; i++) {
if (i !== 0) {
图层列表文本 += " ";
}
图层列表文本 += 匹配图层数组[i].name;
}
var 数据解析分割=图层列表文本.split("_");
//var 实际套花名称=名称部分[0]
var 基码图层宽度 = parseFloat(数据解析分割[1]);
var 基码图层高度 = parseFloat(数据解析分割[2]);
var 缩放比例高度=高度转毫米/基码图层高度*100
var 缩放比例宽度=宽度转毫米/基码图层宽度*100
// alert(基码图层宽度);
} else {
alert("没有找到匹配的图层。");
}
/*
$.writeln("上边距:" + 边距.top);
$.writeln("左边距:" + 边距.left);
$.writeln("下边距:" + 边距.bottom);
$.writeln("右边距:" + 边距.right);
*/8
// 示例用法:
var 毫米 = 300;
var 每英寸像素数 = app.activeDocument.resolution; // 获取当前文档的分辨率(每英寸像素数)
var 扩展像素 = 毫米转像素(毫米, 每英寸像素数);
var 裁切上边距= 边距.top-扩展像素
var 裁切左边距= 边距.left-扩展像素
var 裁切下边距= 边距.bottom+扩展像素
var 裁切右边距= 边距.right+扩展像素
$.writeln(裁切上边距);
$.writeln(裁切左边距);
$.writeln(裁切下边距);
$.writeln(裁切右边距);
裁切图层(裁切上边距,裁切左边距,裁切下边距,裁切右边距)
var 空白裁片模板 = app.activeDocument.layerSets.getByName(大货组名称).layers.getByName(实际裁片名称);
app.activeDocument.activeLayer = 空白裁片模板;
载入选区()
var 缩放定位点的中心坐标=获取当前缩放定位点选区四边距()
var 缩放定位点的Y轴坐标=缩放定位点的中心坐标.top2+(缩放定位点的中心坐标.bottom2-缩放定位点的中心坐标.top2)/2
var 缩放定位点的X轴坐标=缩放定位点的中心坐标.left2+(缩放定位点的中心坐标.right2-缩放定位点的中心坐标.left2)/2
$.writeln("Y轴中心坐标"+缩放定位点的Y轴坐标);
$.writeln("X轴中心坐标"+缩放定位点的X轴坐标);
var 裁片 = app.activeDocument.layers.getByName(裁片名称);
app.activeDocument.activeLayer = 裁片
//var 空白裁片模板 = app.activeDocument.layerSets.getByName(大货组名称).layers.getByName(实际裁片名称 );
//app.activeDocument.activeLayer = 空白裁片模板;
取消选择()
图层按照缩放定位点进行宽高缩放(缩放定位点的X轴坐标,缩放定位点的Y轴坐标,缩放比例高度,缩放比例宽度)
// var 裁片 = app.activeDocument.layers.getByName(裁片名称);
// app.activeDocument.activeLayer = 裁片;
var 空白裁片模板 = app.activeDocument.layerSets.getByName(大货组名称).layers.getByName(实际裁片名称 );
app.activeDocument.activeLayer = 空白裁片模板;
载入选区()
var 裁片 = app.activeDocument.layers.getByName(裁片名称);
app.activeDocument.activeLayer = 裁片
添加图层蒙版()
应用图层蒙版()
裁片.copy();
历史记录回退()
app.activeDocument = currentDocument;
图层选择(当前图层名称);
载入选区();
粘贴图层();
取消选择();
// app.refresh();
var 裁片名称 = 当前图层名称.split("_");
if (裁片名称.length > 1) {
var 角度信息 = 裁片名称[1];
if (角度信息 === "180" || 角度信息 === "-180") {
自由变换();
} else if (角度信息 === "-90") {
逆时针90旋转()
} else if (角度信息 === "90") {
顺时针90旋转()
} else {
// 如果以上条件都不满足,则执行默认的代码
}
//历史记录回退缩放函数()
}
app.activeDocument = 主文档;
历史记录回退缩放函数()
}
}
app.activeDocument = currentDocument;
烧花线添加()//alert("当前码拍好")///////////////////////////////////这里可以填写添加烧花线函数
}
//alert("排版完成,请检查文件!!!")
app.activeDocument = 主文档;
}
// 将像素转换为毫米
function pixelsToMillimeters(pixels) {
// 获取当前文档
var doc = app.activeDocument;
// 获取图像的分辨率(像素/英寸)
var resolution = doc.resolution;
// 计算像素转换为毫米
var inches = pixels / resolution;
var millimeters = inches * 25.4;
return millimeters.toFixed(2); // 保留两位小数
}
function 顺时针90旋转() //自由变换
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
d.putEnumerated(stringIDToTypeID("freeTransformCenterState"), stringIDToTypeID("quadCenterState"), stringIDToTypeID("QCSAverage"));
var d1 = new ActionDescriptor();
d1.putUnitDouble(stringIDToTypeID("horizontal"), stringIDToTypeID("pixelsUnit"), 0);
d1.putUnitDouble(stringIDToTypeID("vertical"), stringIDToTypeID("pixelsUnit"), 0);
d.putObject(stringIDToTypeID("offset"), stringIDToTypeID("offset"), d1);
d.putUnitDouble(stringIDToTypeID("angle"), stringIDToTypeID("angleUnit"), 90);
d.putBoolean(stringIDToTypeID("linked"), true);
d.putEnumerated(charIDToTypeID("Intr"), stringIDToTypeID("interpolationType"), stringIDToTypeID("nearestNeighbor"));
executeAction(stringIDToTypeID("transform"), d, DialogModes.NO);
}
function 逆时针90旋转() //自由变换
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
d.putEnumerated(stringIDToTypeID("freeTransformCenterState"), stringIDToTypeID("quadCenterState"), stringIDToTypeID("QCSAverage"));
var d1 = new ActionDescriptor();
d1.putUnitDouble(stringIDToTypeID("horizontal"), stringIDToTypeID("pixelsUnit"), 0);
d1.putUnitDouble(stringIDToTypeID("vertical"), stringIDToTypeID("pixelsUnit"), 0);
d.putObject(stringIDToTypeID("offset"), stringIDToTypeID("offset"), d1);
d.putUnitDouble(stringIDToTypeID("angle"), stringIDToTypeID("angleUnit"), -90);
d.putBoolean(stringIDToTypeID("linked"), true);
d.putEnumerated(charIDToTypeID("Intr"), stringIDToTypeID("interpolationType"), stringIDToTypeID("nearestNeighbor"));
executeAction(stringIDToTypeID("transform"), d, DialogModes.NO);
}
function 匹配图层名(搜索词) {
// 获取指定图层组中的所有图层
function 获取组中所有图层(组) {
var 图层数组 = [];
var 图层组中图层 = 组.layers;
for (var i = 0; i < 图层组中图层.length; i++) {
var 图层 = 图层组中图层[i];
图层数组.push(图层);
if (图层.typename === "LayerSet") {
var 子图层 = 获取组中所有图层(图层);
图层数组 = 图层数组.concat(子图层);
}
}
return 图层数组;
}
// 获取指定名称的图层组
function 根据名称获取图层组(文档, 组名称) {
var 组 = null;
var 所有图层 = 文档.layers;
for (var i = 0; i < 所有图层.length; i++) {
var 图层 = 所有图层[i];
if (图层.typename === "LayerSet" && 图层.name === 组名称) {
组 = 图层;
break;
}
}
return 组;
}
var 文档 = app.activeDocument;
var 组名称 = "图层基础信息"; // 指定要匹配的图层组名称
var 组 = 根据名称获取图层组(文档, 组名称);
if (组) {
var 图层数组 = 获取组中所有图层(组);
var 模糊匹配图层数组 = [];
// 首先进行模糊匹配
for (var i = 0; i < 图层数组.length; i++) {
var 图层 = 图层数组[i];
if (图层.name.indexOf(搜索词) !== -1) {
模糊匹配图层数组.push(图层);
}
}
// 在模糊匹配结果中进行图层基础信息数组分割过滤
var 精确匹配图层数组 = [];
for (var j = 0; j < 模糊匹配图层数组.length; j++) {
var 模糊匹配图层 = 模糊匹配图层数组[j];
// 进行图层基础信息数组分割过滤
var 图层基础信息数组 = 模糊匹配图层.name.split("_"); // 假设分割符是 "_"
if (图层基础信息数组[0] === 搜索词) {
精确匹配图层数组.push(模糊匹配图层);
}
}
// 返回匹配的图层数组
return 精确匹配图层数组;
} else {
alert('未找到名为"' + 组名称 + '"的图层组。');
return [];
}
}
function 毫米转像素(毫米, 每英寸像素数) {
var 每英寸毫米数 = 25.4;
var 英寸 = 毫米 / 每英寸毫米数;
return Math.round(英寸 * 每英寸像素数);
}
function 图层按照缩放定位点进行宽高缩放(缩放定位点的X轴坐标,缩放定位点的Y轴坐标,缩放比例高度,缩放比例宽度) //自由变换
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
d.putEnumerated(stringIDToTypeID("freeTransformCenterState"), stringIDToTypeID("quadCenterState"), stringIDToTypeID("QCSIndependent"));
var d1 = new ActionDescriptor();
d1.putUnitDouble(stringIDToTypeID("horizontal"), stringIDToTypeID("pixelsUnit"), 缩放定位点的X轴坐标);
d1.putUnitDouble(stringIDToTypeID("vertical"), stringIDToTypeID("pixelsUnit"), 缩放定位点的Y轴坐标);
d.putObject(stringIDToTypeID("position"), stringIDToTypeID("point"), d1);
var d2 = new ActionDescriptor();
d2.putUnitDouble(stringIDToTypeID("horizontal"), stringIDToTypeID("pixelsUnit"), 0);
d2.putUnitDouble(stringIDToTypeID("horizontal"), stringIDToTypeID("pixelsUnit"), 0);
d2.putUnitDouble(stringIDToTypeID("vertical"), stringIDToTypeID("pixelsUnit"), 0);
d.putObject(stringIDToTypeID("offset"), stringIDToTypeID("offset"), d2);
d.putUnitDouble(stringIDToTypeID("width"), stringIDToTypeID("percentUnit"), 缩放比例宽度);
d.putUnitDouble(stringIDToTypeID("height"), stringIDToTypeID("percentUnit"), 缩放比例高度);
d.putEnumerated(charIDToTypeID("Intr"), stringIDToTypeID("interpolationType"), stringIDToTypeID("nearestNeighbor"));
executeAction(stringIDToTypeID("transform"), d, DialogModes.NO);
}
function 裁切图层(裁切上边距,裁切左边距,裁切下边距,裁切右边距) //
{
var d = new ActionDescriptor();
var d1 = new ActionDescriptor();
d1.putUnitDouble(stringIDToTypeID("top"), stringIDToTypeID("pixelsUnit"), 裁切上边距);
d1.putUnitDouble(stringIDToTypeID("left"), stringIDToTypeID("pixelsUnit"), 裁切左边距);
d1.putUnitDouble(stringIDToTypeID("bottom"), stringIDToTypeID("pixelsUnit"),裁切下边距);
d1.putUnitDouble(stringIDToTypeID("right"), stringIDToTypeID("pixelsUnit"), 裁切右边距);
d.putObject(stringIDToTypeID("to"), stringIDToTypeID("rectangle"), d1);
d.putUnitDouble(stringIDToTypeID("angle"), stringIDToTypeID("angleUnit"), 0);
d.putBoolean(stringIDToTypeID("delete"), true);
d.putEnumerated(stringIDToTypeID("cropAspectRatioModeKey"), stringIDToTypeID("cropAspectRatioModeClass"), stringIDToTypeID("pureAspectRatio"));
d.putBoolean(stringIDToTypeID("constrainProportions"), false);
executeAction(stringIDToTypeID("crop"), d, DialogModes.NO);
}
function 获取当前缩放定位点选区四边距() {
var currentDocument = app.activeDocument;
var selectionBounds = currentDocument.selection.bounds;
var top2 = selectionBounds[1].value;
var left2 = selectionBounds[0].value;
var bottom2 = selectionBounds[3].value;
var right2 = selectionBounds[2].value;
return {
top2: top2,
left2: left2,
bottom2: bottom2,
right2: right2
};
}
function 获取当前选区四边距() {
var currentDocument = app.activeDocument;
var selectionBounds = currentDocument.selection.bounds;
var top = selectionBounds[1].value;
var left = selectionBounds[0].value;
var bottom = selectionBounds[3].value;
var right = selectionBounds[2].value;
return {
top: top,
left: left,
bottom: bottom,
right: right
};
}
function 历史记录回退缩放函数() //
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putOffset(stringIDToTypeID("historyState"), -4 );
d.putReference(stringIDToTypeID("null"), r);
executeAction(stringIDToTypeID("select"), d, DialogModes.NO);
}
function 粘贴图层() //粘贴图层
{
var d = new ActionDescriptor();
executeAction(stringIDToTypeID("paste"), d, DialogModes.NO);
}
function 复制图层() //复制图层
{
var d = new ActionDescriptor();
executeAction(stringIDToTypeID("copyEvent"), d, DialogModes.NO);
}
function 载入选区() //载入选区
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("channel"), stringIDToTypeID("selection"));
d.putReference(stringIDToTypeID("null"), r);
var r1 = new ActionReference();
r1.putEnumerated(stringIDToTypeID("channel"), stringIDToTypeID("channel"), stringIDToTypeID("transparencyEnum"));
d.putReference(stringIDToTypeID("to"), r1);
executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
}
function 取消选择() //取消选择
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("channel"), stringIDToTypeID("selection"));
d.putReference(stringIDToTypeID("null"), r);
d.putEnumerated(stringIDToTypeID("to"), stringIDToTypeID("ordinal"), stringIDToTypeID("none"));
executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
}
function 图层选择(当前图层名称) //
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putName(stringIDToTypeID("layer"), 当前图层名称);
d.putReference(stringIDToTypeID("null"), r);
d.putBoolean(stringIDToTypeID("makeVisible"), false);
var list = new ActionList();
list.putInteger(6);
d.putList(stringIDToTypeID("layerID"), list);
executeAction(stringIDToTypeID("select"), d, DialogModes.NO);
}
function 自由变换() //自由变换
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
d.putEnumerated(stringIDToTypeID("freeTransformCenterState"), stringIDToTypeID("quadCenterState"), stringIDToTypeID("QCSAverage"));
var d1 = new ActionDescriptor();
d1.putUnitDouble(stringIDToTypeID("horizontal"), stringIDToTypeID("distanceUnit"), 0);
d1.putUnitDouble(stringIDToTypeID("vertical"), stringIDToTypeID("distanceUnit"), 0);
d.putObject(stringIDToTypeID("offset"), stringIDToTypeID("offset"), d1);
d.putUnitDouble(stringIDToTypeID("width"), stringIDToTypeID("percentUnit"), -100);
d.putUnitDouble(stringIDToTypeID("height"), stringIDToTypeID("percentUnit"), -100);
d.putBoolean(stringIDToTypeID("linked"), true);
d.putEnumerated(charIDToTypeID("Intr"), stringIDToTypeID("interpolationType"), stringIDToTypeID("nearestNeighbor"));
executeAction(stringIDToTypeID("transform"), d, DialogModes.NO);
}
function 选择上一图层() //
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("forwardEnum"));
d.putReference(stringIDToTypeID("null"), r);
d.putBoolean(stringIDToTypeID("makeVisible"), false);
var list = new ActionList();
list.putInteger(8);
d.putList(stringIDToTypeID("layerID"), list);
executeAction(stringIDToTypeID("select"), d, DialogModes.NO);
}
function 添加图层蒙版() //添加图层蒙版
{
var d = new ActionDescriptor();
d.putClass(stringIDToTypeID("new"), stringIDToTypeID("channel"));
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("channel"), stringIDToTypeID("channel"), stringIDToTypeID("mask"));
d.putReference(stringIDToTypeID("at"), r);
d.putEnumerated(stringIDToTypeID("using"), stringIDToTypeID("userMaskEnabled"), stringIDToTypeID("revealSelection"));
executeAction(stringIDToTypeID("make"), d, DialogModes.NO);
}
function 应用图层蒙版() //应用图层蒙版
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("channel"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
d.putBoolean(stringIDToTypeID("apply"), true);
executeAction(stringIDToTypeID("delete"), d, DialogModes.NO);
}
function 拼合所有蒙版() //拼合所有蒙版
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("document"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
executeAction(stringIDToTypeID("e805a6ee-6d75-4b62-b6fe-f5873b5fdf20"), d, DialogModes.NO);
}
function 选择蒙版() //选择蒙版
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("channel"), stringIDToTypeID("channel"), stringIDToTypeID("mask"));
d.putReference(stringIDToTypeID("null"), r);
d.putBoolean(stringIDToTypeID("makeVisible"), false);
executeAction(stringIDToTypeID("select"), d, DialogModes.NO);
}
function 历史记录回退() //
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putOffset(stringIDToTypeID("historyState"), -5);
d.putReference(stringIDToTypeID("null"), r);
executeAction(stringIDToTypeID("select"), d, DialogModes.NO);
}
function 烧花线添加() {
app.activeDocument.suspendHistory("烧花线添加", "烧花线()");
function 烧花线() {
// 遍历当前文档图层
var doc = app.activeDocument;
var layers = doc.layers;
var filteredLayers = [];
// 遍历图层筛选以P开头的图层
for (var i = 0; i < layers.length; i++) {
var layer = layers[i];
if (layer.name.charAt(0) === 'P') {
filteredLayers.push(layer);
}
}
空置图层()
// 输出图层名称
for (var j = 0; j < filteredLayers.length; j++) {
var filteredLayer = filteredLayers[j];
var 裁片底图名称=filteredLayer.name;
多选图层(裁片底图名称);
// alert(filteredLayer.name);
}
合并图层();
置为顶层();
画布大小();
var layer = app.activeDocument.activeLayer;
layer.name = "底图";
恢复默认颜色()
矩形选框像素点()
//色彩范围()
填充();
魔棒烧花线()
新建图层()
var layer2 = app.activeDocument.activeLayer;
layer2.name = "剪口";
扩展2();
恢复止口线默认颜色()
填充();
矩形选框准备删除()
清除();
魔棒();
扩展();
选择反向();
清除();
var 底图 = app.activeDocument.layers.getByName( "底图");
app.activeDocument.activeLayer=底图;
矩形选框准备删除()
清除();
置为底层()
图层样式()
取消选择()
function 多选图层(裁片底图名称) //
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putName(stringIDToTypeID("layer"), 裁片底图名称);
d.putReference(stringIDToTypeID("null"), r);
d.putEnumerated(stringIDToTypeID("selectionModifier"), stringIDToTypeID("selectionModifierType"), stringIDToTypeID("addToSelection"));
d.putBoolean(stringIDToTypeID("makeVisible"), false);
var list = new ActionList();
list.putInteger(4);
d.putList(stringIDToTypeID("layerID"), list);
executeAction(stringIDToTypeID("select"), d, DialogModes.NO);
}
function 空置图层() //
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
executeAction(stringIDToTypeID("selectNoLayers"), d, DialogModes.NO);
}
function 恢复止口线默认颜色() //取消选择
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("color"), stringIDToTypeID("foregroundColor"));
d.putReference(stringIDToTypeID("null"), r);
var d1 = new ActionDescriptor();
d1.putDouble(stringIDToTypeID("cyan"), 20);
d1.putDouble(stringIDToTypeID("magenta"), 0);
d1.putDouble(stringIDToTypeID("yellowColor"), 0);
d1.putDouble(stringIDToTypeID("black"), 0);
d.putObject(stringIDToTypeID("to"), stringIDToTypeID("CMYKColorClass"), d1);
d.putString(stringIDToTypeID("source"), "photoshopPicker");
executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
}
function 合并图层() //合并图层
{
var d = new ActionDescriptor();
executeAction(stringIDToTypeID("mergeLayersNew"), d, DialogModes.NO);
}
function 恢复默认颜色() //
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("color"), stringIDToTypeID("colors"));
d.putReference(stringIDToTypeID("null"), r);
executeAction(stringIDToTypeID("reset"), d, DialogModes.NO);
}
function 魔棒烧花线() //魔棒
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("channel"), stringIDToTypeID("selection"));
d.putReference(stringIDToTypeID("null"), r);
var d1 = new ActionDescriptor();
d1.putUnitDouble(stringIDToTypeID("horizontal"), stringIDToTypeID("distanceUnit"), 0);
d1.putUnitDouble(stringIDToTypeID("vertical"), stringIDToTypeID("distanceUnit"), 0);
d.putObject(stringIDToTypeID("to"), stringIDToTypeID("point"), d1);
d.putInteger(stringIDToTypeID("tolerance"), 6);
d.putBoolean(stringIDToTypeID("contiguous"), false);
executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
}
function 矩形选框像素点() //矩形选框
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("channel"), stringIDToTypeID("selection"));
d.putReference(stringIDToTypeID("null"), r);
var d1 = new ActionDescriptor();
d1.putUnitDouble(stringIDToTypeID("top"), stringIDToTypeID("distanceUnit"), 0);
d1.putUnitDouble(stringIDToTypeID("left"), stringIDToTypeID("distanceUnit"), 0);
d1.putUnitDouble(stringIDToTypeID("bottom"), stringIDToTypeID("distanceUnit"), 0.48);
d1.putUnitDouble(stringIDToTypeID("right"), stringIDToTypeID("distanceUnit"), 0.48);
d.putObject(stringIDToTypeID("to"), stringIDToTypeID("rectangle"), d1);
executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
}
function 置为底层() //置为底层
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
var r1 = new ActionReference();
r1.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("back"));
d.putReference(stringIDToTypeID("to"), r1);
executeAction(stringIDToTypeID("move"), d, DialogModes.NO);
}
function 置为顶层() //置为顶层
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
var r1 = new ActionReference();
r1.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("front"));
d.putReference(stringIDToTypeID("to"), r1);
executeAction(stringIDToTypeID("move"), d, DialogModes.NO);
}
function 色彩范围() //色彩范围
{
var d = new ActionDescriptor();
d.putInteger(stringIDToTypeID("fuzziness"), 40);
var d1 = new ActionDescriptor();
d1.putDouble(stringIDToTypeID("luminance"), 0);
d1.putDouble(stringIDToTypeID("a"), 0);
d1.putDouble(stringIDToTypeID("b"), 0);
d.putObject(stringIDToTypeID("minimum"), stringIDToTypeID("labColor"), d1);
var d2 = new ActionDescriptor();
d2.putDouble(stringIDToTypeID("luminance"), 0);
d2.putDouble(stringIDToTypeID("a"), 0);
d2.putDouble(stringIDToTypeID("b"), 0);
d.putObject(stringIDToTypeID("maximum"), stringIDToTypeID("labColor"), d2);
d.putInteger(stringIDToTypeID("colorModel"), 0);
executeAction(stringIDToTypeID("colorRange"), d, DialogModes.NO);
}
function 新建图层() //新建图层
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putClass(stringIDToTypeID("layer"));
d.putReference(stringIDToTypeID("null"), r);
d.putInteger(stringIDToTypeID("layerID"), 33);
executeAction(stringIDToTypeID("make"), d, DialogModes.NO);
}
function 扩展2() //扩展
{
var d = new ActionDescriptor();
d.putUnitDouble(stringIDToTypeID("by"), stringIDToTypeID("pixelsUnit"), 1);
d.putBoolean(stringIDToTypeID("selectionModifyEffectAtCanvasBounds"), false);
executeAction(stringIDToTypeID("expand"), d, DialogModes.NO);
}
function 填充() //填充
{
var d = new ActionDescriptor();
d.putEnumerated(stringIDToTypeID("using"), stringIDToTypeID("fillContents"), stringIDToTypeID("foregroundColor"));
d.putUnitDouble(stringIDToTypeID("opacity"), stringIDToTypeID("percentUnit"), 100);
d.putEnumerated(stringIDToTypeID("mode"), stringIDToTypeID("blendMode"), stringIDToTypeID("normal"));
executeAction(stringIDToTypeID("fill"), d, DialogModes.NO);
}
function 画布大小() //画布大小
{
var d = new ActionDescriptor();
d.putBoolean(stringIDToTypeID("relative"), true);
d.putUnitDouble(stringIDToTypeID("width"), stringIDToTypeID("distanceUnit"), 40);
d.putUnitDouble(stringIDToTypeID("height"), stringIDToTypeID("distanceUnit"), 40);
d.putEnumerated(stringIDToTypeID("horizontal"), stringIDToTypeID("horizontalLocation"), stringIDToTypeID("center"));
d.putEnumerated(stringIDToTypeID("vertical"), stringIDToTypeID("verticalLocation"), stringIDToTypeID("center"));
executeAction(stringIDToTypeID("canvasSize"), d, DialogModes.NO);
}
function 魔棒() //魔棒
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("channel"), stringIDToTypeID("selection"));
d.putReference(stringIDToTypeID("null"), r);
var d1 = new ActionDescriptor();
d1.putUnitDouble(stringIDToTypeID("horizontal"), stringIDToTypeID("pixelsUnit"), 3);
d1.putUnitDouble(stringIDToTypeID("vertical"), stringIDToTypeID("pixelsUnit"), 3);
d.putObject(stringIDToTypeID("to"), stringIDToTypeID("point"), d1);
d.putInteger(stringIDToTypeID("tolerance"), 6);
executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
}
function 矩形选框准备删除() //矩形选框
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("channel"), stringIDToTypeID("selection"));
d.putReference(stringIDToTypeID("null"), r);
var d1 = new ActionDescriptor();
d1.putUnitDouble(stringIDToTypeID("top"), stringIDToTypeID("distanceUnit"), 0);
d1.putUnitDouble(stringIDToTypeID("left"), stringIDToTypeID("distanceUnit"), 0);
d1.putUnitDouble(stringIDToTypeID("bottom"), stringIDToTypeID("distanceUnit"), 0.96);
d1.putUnitDouble(stringIDToTypeID("right"), stringIDToTypeID("distanceUnit"), 0.96);
d.putObject(stringIDToTypeID("to"), stringIDToTypeID("rectangle"), d1);
executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
}
function 扩展() //扩展
{
var d = new ActionDescriptor();
d.putUnitDouble(stringIDToTypeID("by"), stringIDToTypeID("pixelsUnit"), 25);
d.putBoolean(stringIDToTypeID("selectionModifyEffectAtCanvasBounds"), false);
executeAction(stringIDToTypeID("expand"), d, DialogModes.NO);
}
function 选择反向() //选择反向
{
var d = new ActionDescriptor();
executeAction(stringIDToTypeID("inverse"), d, DialogModes.NO);
}
function 清除() //清除
{
app.activeDocument.selection.clear();
}
function 图层样式() //图层样式
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("property"), stringIDToTypeID("layerEffects"));
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
var d1 = new ActionDescriptor();
d1.putUnitDouble(stringIDToTypeID("scale"), stringIDToTypeID("percentUnit"), 12);
var d2 = new ActionDescriptor();
d2.putBoolean(stringIDToTypeID("enabled"), true);
d2.putBoolean(stringIDToTypeID("present"), true);
d2.putBoolean(stringIDToTypeID("showInDialog"), true);
d2.putEnumerated(stringIDToTypeID("style"), stringIDToTypeID("frameStyle"), stringIDToTypeID("outsetFrame"));
d2.putEnumerated(stringIDToTypeID("paintType"), stringIDToTypeID("frameFill"), stringIDToTypeID("solidColor"));
d2.putEnumerated(stringIDToTypeID("mode"), stringIDToTypeID("blendMode"), stringIDToTypeID("normal"));
d2.putUnitDouble(stringIDToTypeID("opacity"), stringIDToTypeID("percentUnit"), 100);
d2.putUnitDouble(stringIDToTypeID("size"), stringIDToTypeID("pixelsUnit"), 16);
var d3 = new ActionDescriptor();
d3.putDouble(stringIDToTypeID("red"), 255);
d3.putDouble(stringIDToTypeID("green"), 0);
d3.putDouble(stringIDToTypeID("blue"), 0);
d2.putObject(stringIDToTypeID("color"), stringIDToTypeID("RGBColor"), d3);
d2.putBoolean(stringIDToTypeID("overprint"), false);
d1.putObject(stringIDToTypeID("frameFX"), stringIDToTypeID("frameFX"), d2);
d.putObject(stringIDToTypeID("to"), stringIDToTypeID("layerEffects"), d1);
executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
}
function 取消选择() //取消选择
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("channel"), stringIDToTypeID("selection"));
d.putReference(stringIDToTypeID("null"), r);
d.putEnumerated(stringIDToTypeID("to"), stringIDToTypeID("ordinal"), stringIDToTypeID("none"));
executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
}
}
}
"""

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,385 @@
dxf15_jscode = """
function 图层自动编组2() {
app.activeDocument.suspendHistory("图层自动编组", "图层自动编组()");
}
function 图层自动编组(){
var currentDocument = app.activeDocument;
var matchCount = 0; // 匹配到的数值计数
var existingPatternSet = false;
var layerNames = []; // 保存匹配到的图层名称的数组
// 遍历图层
for (var j = 0; j < currentDocument.layers.length; j++) {
var layer = currentDocument.layers[j];
var layerName = layer.name;
// 检查图层名称是否以P开头并且后面跟着数字
if (/^P\d+$/.test(layerName)) {
matchCount++;
layerNames.push(layer); // 将匹配到的图层添加到数组中
}
}
// 输出匹配到的数值个数
$.writeln("匹配到的数值个数:" + matchCount);
// 遍历匹配到的图层名称
for (var i = 0; i < layerNames.length; i++) {
var layerName = layerNames[i].name;
// $.writeln("匹配到的图层名称:" + layerName);
var 当前花样图层 = app.activeDocument.layers.getByName(layerName);
app.activeDocument.activeLayer = 当前花样图层;
图层编组main()
app.activeDocument.activeLayer.name=layerName
}
}
function 图层编组main() //图层编组
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putClass(stringIDToTypeID("layerSection"));
d.putReference(stringIDToTypeID("null"), r);
var r1 = new ActionReference();
r1.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("from"), r1);
d.putInteger(stringIDToTypeID("layerSectionStart"), 43);
d.putInteger(stringIDToTypeID("layerSectionEnd"), 44);
d.putString(stringIDToTypeID("name"), "main");
executeAction(stringIDToTypeID("make"), d, DialogModes.NO);
}
function 快速超级链接2() {
app.activeDocument.suspendHistory("快速超链接", "快速超级链接()");
}
function 快速超级链接() {
var 导出目录 = Folder.selectDialog("选择超链接素材目录");
if (!导出目录) {
alert("未选择导出目录。操作已取消。");
return;
}
画布大小()
app.preferences.rulerUnits = Units.PIXELS
var currentDocument = app.activeDocument;
var matchCount = 0; // 匹配到的数值计数
var existingPatternSet = false;
var layerNames = []; // 保存匹配到的图层名称的数组
// 遍历图层
for (var j = 0; j < currentDocument.layers.length; j++) {
var layer = currentDocument.layers[j];
var layerName = layer.name;
// 检查图层名称是否以P开头并且后面跟着数字
if (/^P\d+$/.test(layerName)) {
matchCount++;
layerNames.push(layer); // 将匹配到的图层添加到数组中
}
}
// 输出匹配到的数值个数
// $.writeln("匹配到的数值个数:" + matchCount);
// 遍历匹配到的图层名称
for (var i = 0; i < layerNames.length; i++) {
var layerName = layerNames[i].name;
$.writeln("匹配到的图层名称:" + layerName);
var 当前花样图层 = app.activeDocument.layers.getByName(layerName);
app.activeDocument.activeLayer = 当前花样图层;
切换mask()
载入选区()
var 边距 = 获取当前选区四边距();
var 毫米 = 130;
var 每英寸像素数 = app.activeDocument.resolution; // 获取当前文档的分辨率(每英寸像素数)
var 扩展像素 = 毫米转像素(毫米, 每英寸像素数);
var 裁切上边距= 边距.top-扩展像素
var 裁切左边距= 边距.left-扩展像素
var 裁切下边距= 边距.bottom+扩展像素
var 裁切右边距= 边距.right+扩展像素
var selRegion = [
[裁切左边距,裁切上边距],
[裁切右边距,裁切上边距],
[裁切右边距,裁切下边距],
[裁切左边距,裁切下边距]
];
app.activeDocument.selection.select(selRegion, SelectionType.REPLACE);
新建图层()
app.activeDocument.selection.select(selRegion, SelectionType.REPLACE);
var c = new SolidColor();
c.rgb.hexValue = "FFFFFF";
app.activeDocument.selection.fill(c);
后移一层()
app.activeDocument.activeLayer = 当前花样图层;
切换mask()
载入选区()
删除图层蒙版()
创建剪贴蒙版()
向下合并()
新建文档()
当前花样图层 = app.activeDocument.activeLayer
app.activeDocument.crop( 当前花样图层.bounds, 0);
var 文件路径 = 导出目录 + "/" + layerName + ".tif";
tiffOptions = new TiffSaveOptions();
app.activeDocument.saveAs(new File(文件路径), tiffOptions);
app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
app.activeDocument=currentDocument
转换为智能对象()
重新链接到文件(文件路径)
添加图层蒙版()
//当前图层=app.activeDocument.activeLayer
//当前图层.name=layerName
}
}
function 新建文档() //复制图层
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putClass(stringIDToTypeID("document"));
d.putReference(stringIDToTypeID("null"), r);
var r1 = new ActionReference();
r1.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("using"), r1);
d.putInteger(stringIDToTypeID("version"), 5);
executeAction(stringIDToTypeID("make"), d, DialogModes.NO);
}
function 转换为智能对象() //转换为智能对象
{
var d = new ActionDescriptor();
executeAction(stringIDToTypeID("newPlacedLayer"), d, DialogModes.NO);
}
function 重新链接到文件(文件路径) //重新链接到文件
{
var d = new ActionDescriptor();
d.putPath(stringIDToTypeID("null"), new File(文件路径));
d.putInteger(stringIDToTypeID("layerID"), 94);
executeAction(stringIDToTypeID("placedLayerRelinkToFile"), d, DialogModes.NO);
}
function 切换mask() //取消选择
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("channel"), stringIDToTypeID("channel"), stringIDToTypeID("mask"));
d.putReference(stringIDToTypeID("null"), r);
d.putBoolean(stringIDToTypeID("makeVisible"), false);
executeAction(stringIDToTypeID("select"), d, DialogModes.NO);
}
function 毫米转像素(毫米, 每英寸像素数) {
var 每英寸毫米数 = 25.4;
var 英寸 = 毫米 / 每英寸毫米数;
return Math.round(英寸 * 每英寸像素数);
}
function 画布大小() //画布大小
{
var d = new ActionDescriptor();
d.putBoolean(stringIDToTypeID("relative"), true);
d.putUnitDouble(stringIDToTypeID("width"), stringIDToTypeID("distanceUnit"), 850.56);
d.putUnitDouble(stringIDToTypeID("height"), stringIDToTypeID("distanceUnit"), 850.56);
d.putEnumerated(stringIDToTypeID("horizontal"), stringIDToTypeID("horizontalLocation"), stringIDToTypeID("center"));
d.putEnumerated(stringIDToTypeID("vertical"), stringIDToTypeID("verticalLocation"), stringIDToTypeID("center"));
executeAction(stringIDToTypeID("canvasSize"), d, DialogModes.NO);
}
function 载入选区() //载入选区
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("channel"), stringIDToTypeID("selection"));
d.putReference(stringIDToTypeID("null"), r);
var r1 = new ActionReference();
r1.putEnumerated(stringIDToTypeID("channel"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("to"), r1);
executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
}
function 获取当前选区四边距() {
var currentDocument = app.activeDocument;
var selectionBounds = currentDocument.selection.bounds;
var top = selectionBounds[1].value;
var left = selectionBounds[0].value;
var bottom = selectionBounds[3].value;
var right = selectionBounds[2].value;
return {
top: top,
left: left,
bottom: bottom,
right: right
};
}
function 新建图层() //新建图层
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putClass(stringIDToTypeID("layer"));
d.putReference(stringIDToTypeID("null"), r);
d.putInteger(stringIDToTypeID("layerID"), 135);
executeAction(stringIDToTypeID("make"), d, DialogModes.NO);
}
function 后移一层() //后移一层
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
var r1 = new ActionReference();
r1.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("previous"));
d.putReference(stringIDToTypeID("to"), r1);
executeAction(stringIDToTypeID("move"), d, DialogModes.NO);
}
function 删除图层蒙版() //删除图层蒙版
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("channel"), stringIDToTypeID("channel"), stringIDToTypeID("mask"));
d.putReference(stringIDToTypeID("null"), r);
executeAction(stringIDToTypeID("delete"), d, DialogModes.NO);
}
function 载入选区() //载入选区
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("channel"), stringIDToTypeID("selection"));
d.putReference(stringIDToTypeID("null"), r);
var r1 = new ActionReference();
r1.putEnumerated(stringIDToTypeID("channel"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("to"), r1);
executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
}
function 删除图层蒙版() //删除图层蒙版
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("channel"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
executeAction(stringIDToTypeID("delete"), d, DialogModes.NO);
}
function 向下合并() //向下合并
{
var d = new ActionDescriptor();
executeAction(stringIDToTypeID("mergeLayersNew"), d, DialogModes.NO);
}
function 添加图层蒙版() //添加图层蒙版
{
var d = new ActionDescriptor();
d.putClass(stringIDToTypeID("new"), stringIDToTypeID("channel"));
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("channel"), stringIDToTypeID("channel"), stringIDToTypeID("mask"));
d.putReference(stringIDToTypeID("at"), r);
d.putEnumerated(stringIDToTypeID("using"), stringIDToTypeID("userMaskEnabled"), stringIDToTypeID("revealSelection"));
executeAction(stringIDToTypeID("make"), d, DialogModes.NO);
}
function 创建剪贴蒙版() //创建剪贴蒙版
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
executeAction(stringIDToTypeID("groupEvent"), d, DialogModes.NO);
}
"""

View File

@@ -0,0 +1,587 @@
dxf16_jscode = """
function 快速定位码链接() {
app.activeDocument.suspendHistory("快速定位码链接", "花样图层导出()");
}
function 花样图层导出() {
var 导出目录 = Folder.selectDialog("选择外链素材目录");
if (!导出目录) {
alert("未选择导出目录。操作已取消。");
return;
}
花样图层导出为TIF透明底(导出目录)
// 花样图层导出为TIF(导出目录);
}
function 花样图层导出为TIF透明底(导出目录) {
app.preferences.rulerUnits = Units.MM;
var doc = app.activeDocument;
var 扩展毫米数=80
// 获取文档中的所有图层
var allLayers = doc.layers;
var 名称数组 = [];
// 循环遍历所有图层
for (var i = 0; i < allLayers.length; i++) {
// 检查图层是否是图层组
if (allLayers[i] instanceof LayerSet) {
// 获取图层组中的所有子图层
subLayers = allLayers[i].layers;
图层组名称=allLayers[i].name
文档名称=app.activeDocument.name
文档名称去除后缀 = 文档名称.replace(/\.[^\.]+$/, "");
// 检查图层组是否包含子图层
if (subLayers.length > 0) {
// 获取图层组中最后一个子图层的名称
var lastSubLayer = subLayers[subLayers.length - 1];
var lastSubLayerName = lastSubLayer.name;
var lastSubLayerName = lastSubLayer.name;
FastSubLayer = subLayers[0];
FastSubLayername= FastSubLayer.name
//alert(SastSubLayerName)
// 输出图层组名称和最后一个子图层的名称
if (图层组名称 === "填充底图") {
for (var j = 0; j < subLayers.length; j++) {
// alert(subLayers[j].name);
填充底图组内部循环名称 = subLayers[j].name
填充底图循环素材 = app.activeDocument.layerSets.getByName("填充底图").layers.getByName(填充底图组内部循环名称);
app.activeDocument.activeLayer = 填充底图循环素材;
新建文档()
// 合并图层()
载入选区()
裁剪()
名称=文档名称去除后缀+"-("+填充底图组内部循环名称 +")-填充底图"
名称数组.push('"' + 名称 + '"');
制作图案预设(名称)
app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
app.activeDocument=doc
// 执行某一个操作(例如,设置图层组的可见性)
// alert("测试")
}
// 手动创建JSON格式的字符串
var jsonStr = '[' + 名称数组.join(', ') + ']';
// 创建一个文件对象指向桌面
var file = new File(导出目录 + "/名称数据.json");
// 打开文件写入JSON字符串然后关闭文件
file.open('w');
file.write(jsonStr);
file.close();
} else {
// 执行别的操作(例如,隐藏其他图层组)
空白裁片模板 = app.activeDocument.layerSets.getByName(图层组名称).layers.getByName(lastSubLayerName);
app.activeDocument.activeLayer = 空白裁片模板;
新建图层()
app.activeDocument.activeLayer.name="最大白边值"
裁片边界 = lastSubLayer.bounds;
扩展值 = 毫米转像素(扩展毫米数); //50cm
裁片边界_左 = 毫米转像素(裁片边界[0]) - 扩展值;
裁片边界_上 = 毫米转像素(裁片边界[1]) - 扩展值;
裁片边界_右 = 毫米转像素(裁片边界[2]) + 扩展值;
裁片边界_下 = 毫米转像素(裁片边界[3]) + 扩展值;
var selRegion = [
[裁片边界_左,裁片边界_上],
[裁片边界_右,裁片边界_上],
[裁片边界_右,裁片边界_下],
[裁片边界_左,裁片边界_下]
];
app.activeDocument.selection.select(selRegion, SelectionType.REPLACE);
背景切换();
恢复白底();
填充();
隐藏图层();
裁片图层组 = app.activeDocument.layerSets.getByName(图层组名称)
app.activeDocument.activeLayer = 裁片图层组 ;
新建文档()
空白裁片模板 = app.activeDocument.layerSets.getByName(图层组名称).layers.getByName(lastSubLayerName);
app.activeDocument.activeLayer = 空白裁片模板;
删除图层()
最大白边值=app.activeDocument.layerSets.getByName(图层组名称).layers.getByName("最大白边值");
app.activeDocument.activeLayer = 最大白边值;
app.activeDocument.crop(最大白边值.bounds, 0);
// 保存为TIF
var 文件路径 = 导出目录 + "/" + 图层组名称 + ".tif";
tiffOptions = new TiffSaveOptions();
app.activeDocument.saveAs(new File(文件路径), tiffOptions);
app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
app.activeDocument=doc
最大白边值=app.activeDocument.layerSets.getByName(图层组名称).layers.getByName(FastSubLayername);
app.activeDocument.activeLayer = 最大白边值;
//上移图层()
多选图层()
转换为智能对象()
释放剪贴蒙版()
栅格化图层()
选择下一图层()
新建图层()
背景切换();
恢复白底();
填充();
选择上一图层()
添加图层蒙版()
向下合并()
转换为智能对象()
重新链接到文件(文件路径)
创建剪贴蒙版()
}
}
}
}
}
function 恢复白底() //删除图层
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("color"), stringIDToTypeID("colors"));
d.putReference(stringIDToTypeID("null"), r);
executeAction(stringIDToTypeID("exchange"), d, DialogModes.NO);
}
function 创建剪贴蒙版() //创建剪贴蒙版
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
executeAction(stringIDToTypeID("groupEvent"), d, DialogModes.NO);
}
function 制作图案预设(名称) //
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putClass(stringIDToTypeID("pattern"));
d.putReference(stringIDToTypeID("null"), r);
var r1 = new ActionReference();
r1.putProperty(stringIDToTypeID("property"), stringIDToTypeID("selection"));
r1.putEnumerated(stringIDToTypeID("document"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("using"), r1);
d.putString(stringIDToTypeID("name"), 名称);
executeAction(stringIDToTypeID("make"), d, DialogModes.NO);
}
function mergeLayersNew_72799682617188() //
{
var d = new ActionDescriptor();
executeAction(stringIDToTypeID("mergeLayersNew"), d, DialogModes.NO);
}
function 合并图层() //
{
var d = new ActionDescriptor();
executeAction(stringIDToTypeID("mergeLayersNew"), d, DialogModes.NO);
}
function 背景切换() //
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("color"), stringIDToTypeID("colors"));
d.putReference(stringIDToTypeID("null"), r);
executeAction(stringIDToTypeID("reset"), d, DialogModes.NO);
}
function 图层可见性show() //图层可见性
{
var d = new ActionDescriptor();
var list = new ActionList();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
list.putReference(r);
d.putList(stringIDToTypeID("null"), list);
executeAction(stringIDToTypeID("show"), d, DialogModes.NO);
}
function 裁剪() //裁剪
{
var d = new ActionDescriptor();
d.putBoolean(stringIDToTypeID("delete"), true);
executeAction(stringIDToTypeID("crop"), d, DialogModes.NO);
}
function 重新链接到文件(文件路径) //重新链接到文件
{
var d = new ActionDescriptor();
d.putPath(stringIDToTypeID("null"), new File(文件路径));
d.putInteger(stringIDToTypeID("layerID"), 94);
executeAction(stringIDToTypeID("placedLayerRelinkToFile"), d, DialogModes.NO);
}
function 转换为智能对象() //转换为智能对象
{
var d = new ActionDescriptor();
executeAction(stringIDToTypeID("newPlacedLayer"), d, DialogModes.NO);
}
function 载入选区() //载入选区
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("channel"), stringIDToTypeID("selection"));
d.putReference(stringIDToTypeID("null"), r);
var r1 = new ActionReference();
r1.putEnumerated(stringIDToTypeID("channel"), stringIDToTypeID("channel"), stringIDToTypeID("transparencyEnum"));
d.putReference(stringIDToTypeID("to"), r1);
executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
}
function 向下合并() //向下合并
{
var d = new ActionDescriptor();
executeAction(stringIDToTypeID("mergeLayersNew"), d, DialogModes.NO);
}
function 添加图层蒙版() //添加图层蒙版
{
var d = new ActionDescriptor();
d.putClass(stringIDToTypeID("new"), stringIDToTypeID("channel"));
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("channel"), stringIDToTypeID("channel"), stringIDToTypeID("mask"));
d.putReference(stringIDToTypeID("at"), r);
d.putEnumerated(stringIDToTypeID("using"), stringIDToTypeID("userMaskEnabled"), stringIDToTypeID("revealSelection"));
executeAction(stringIDToTypeID("make"), d, DialogModes.NO);
}
function 上移图层() //
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("forwardEnum"));
d.putReference(stringIDToTypeID("null"), r);
d.putBoolean(stringIDToTypeID("makeVisible"), false);
var list = new ActionList();
list.putInteger(11);
d.putList(stringIDToTypeID("layerID"), list);
executeAction(stringIDToTypeID("select"), d, DialogModes.NO);
}
function 毫米转像素(毫米)
{
//厘米转像素
doc_w = app.activeDocument.width;
//用户设定的厘米数 支持小数
user_mm = UnitValue(毫米,"mm");
user_px = user_mm.as("px")*app.activeDocument.resolution/72;
return user_px;
}
function 删除图层() //删除图层
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
var list = new ActionList();
list.putInteger(22);
d.putList(stringIDToTypeID("layerID"), list);
executeAction(stringIDToTypeID("delete"), d, DialogModes.NO);
}
function 多选图层(SastSubLayerName) //
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putName(stringIDToTypeID("layer"), "最大白边值");
d.putReference(stringIDToTypeID("null"), r);
d.putEnumerated(stringIDToTypeID("selectionModifier"), stringIDToTypeID("selectionModifierType"), stringIDToTypeID("addToSelectionContinuous"));
d.putBoolean(stringIDToTypeID("makeVisible"), false);
var list = new ActionList();
list.putInteger(115);
d.putList(stringIDToTypeID("layerID"), list);
executeAction(stringIDToTypeID("select"), d, DialogModes.NO);
}
function 新建图层() //新建图层
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putClass(stringIDToTypeID("layer"));
d.putReference(stringIDToTypeID("null"), r);
var d1 = new ActionDescriptor();
d1.putBoolean(stringIDToTypeID("group"), true);
d.putObject(stringIDToTypeID("using"), stringIDToTypeID("layer"), d1);
d.putInteger(stringIDToTypeID("layerID"), 22);
executeAction(stringIDToTypeID("make"), d, DialogModes.NO);
}
function 释放剪贴蒙版() //释放剪贴蒙版
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
executeAction(stringIDToTypeID("ungroup"), d, DialogModes.NO);
}
function 添加图层蒙版() //添加图层蒙版
{
var d = new ActionDescriptor();
d.putClass(stringIDToTypeID("new"), stringIDToTypeID("channel"));
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("channel"), stringIDToTypeID("channel"), stringIDToTypeID("mask"));
d.putReference(stringIDToTypeID("at"), r);
d.putEnumerated(stringIDToTypeID("using"), stringIDToTypeID("userMaskEnabled"), stringIDToTypeID("revealSelection"));
executeAction(stringIDToTypeID("make"), d, DialogModes.NO);
}
function 向下合并() //向下合并
{
var d = new ActionDescriptor();
executeAction(stringIDToTypeID("mergeLayersNew"), d, DialogModes.NO);
}
function 栅格化图层() //栅格化图层
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
executeAction(stringIDToTypeID("rasterizeLayer"), d, DialogModes.NO);
}
function 选择下一图层() //
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("backwardEnum"));
d.putReference(stringIDToTypeID("null"), r);
d.putBoolean(stringIDToTypeID("makeVisible"), false);
var list = new ActionList();
list.putInteger(314);
d.putList(stringIDToTypeID("layerID"), list);
executeAction(stringIDToTypeID("select"), d, DialogModes.NO);
}
function 选择上一图层() //
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("forwardEnum"));
d.putReference(stringIDToTypeID("null"), r);
d.putBoolean(stringIDToTypeID("makeVisible"), false);
var list = new ActionList();
list.putInteger(369);
d.putList(stringIDToTypeID("layerID"), list);
executeAction(stringIDToTypeID("select"), d, DialogModes.NO);
}
function 新建图层() //新建图层
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putClass(stringIDToTypeID("layer"));
d.putReference(stringIDToTypeID("null"), r);
d.putInteger(stringIDToTypeID("layerID"), 373);
executeAction(stringIDToTypeID("make"), d, DialogModes.NO);
}
function 恢复白底() //删除图层
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("color"), stringIDToTypeID("colors"));
d.putReference(stringIDToTypeID("null"), r);
executeAction(stringIDToTypeID("exchange"), d, DialogModes.NO);
}
function 背景切换() //
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("color"), stringIDToTypeID("colors"));
d.putReference(stringIDToTypeID("null"), r);
executeAction(stringIDToTypeID("reset"), d, DialogModes.NO);
}
function 填充() //填充
{
var d = new ActionDescriptor();
d.putEnumerated(stringIDToTypeID("using"), stringIDToTypeID("fillContents"), stringIDToTypeID("foregroundColor"));
d.putUnitDouble(stringIDToTypeID("opacity"), stringIDToTypeID("percentUnit"), 100);
d.putEnumerated(stringIDToTypeID("mode"), stringIDToTypeID("blendMode"), stringIDToTypeID("normal"));
executeAction(stringIDToTypeID("fill"), d, DialogModes.NO);
}
function 填充() //填充
{
var d = new ActionDescriptor();
d.putEnumerated(stringIDToTypeID("using"), stringIDToTypeID("fillContents"), stringIDToTypeID("foregroundColor"));
d.putUnitDouble(stringIDToTypeID("opacity"), stringIDToTypeID("percentUnit"), 100);
d.putEnumerated(stringIDToTypeID("mode"), stringIDToTypeID("blendMode"), stringIDToTypeID("normal"));
executeAction(stringIDToTypeID("fill"), d, DialogModes.NO);
}
function 隐藏图层() //
{
var d = new ActionDescriptor();
var list = new ActionList();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
list.putReference(r);
d.putList(stringIDToTypeID("null"), list);
executeAction(stringIDToTypeID("hide"), d, DialogModes.NO);
}
function 新建文档() //复制图层
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putClass(stringIDToTypeID("document"));
d.putReference(stringIDToTypeID("null"), r);
var r1 = new ActionReference();
r1.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("using"), r1);
d.putInteger(stringIDToTypeID("version"), 5);
executeAction(stringIDToTypeID("make"), d, DialogModes.NO);
}
"""

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,284 @@
dxf18_jscode = """
function 龙服的快速换图(){
// 强制使用 UTF-8 编码
#target photoshop
$.localize = true;
// 创建对话框
var dialog = new Window("dialog");
dialog.text = "快速换图特定版本";
dialog.orientation = "column";
dialog.alignChildren = ["left","top"];
dialog.spacing = 10;
dialog.margins = 16;
// 大货模板文件夹选择面板
var templatePanel = dialog.add("panel", undefined, "大货模板文件夹选择");
templatePanel.orientation = "row";
templatePanel.alignChildren = ["left","center"];
templatePanel.spacing = 10;
templatePanel.margins = 10;
// 大货模板文件夹路径文本框
var templatePathEditText = templatePanel.add('edittext', undefined, '', { properties: { readonly: true } });
templatePathEditText.preferredSize.width = 300;
// 大货模板路径选择按钮
var selectTemplateButton = templatePanel.add("button", undefined, "选择文件夹");
selectTemplateButton.onClick = function() {
var selectedFolder = Folder.selectDialog("选择大货模板文件夹");
if (selectedFolder != null) {
templatePathEditText.text = selectedFolder.fsName;
// alert( templatePathEditText.text)
updateFileNames(selectedFolder);
}
};
// 切片裁片文件夹选择面板
var slicePanel = dialog.add("panel", undefined, "切片裁片文件夹选择");
slicePanel.orientation = "row";
slicePanel.alignChildren = ["left","center"];
slicePanel.spacing = 10;
slicePanel.margins = 10;
// 切片裁片文件夹路径文本框
var slicePathEditText = slicePanel.add('edittext', undefined, '', { properties: { readonly: true } });
slicePathEditText.preferredSize.width = 300;
// 切片裁片路径选择按钮
var selectSliceButton = slicePanel.add("button", undefined, "选择文件夹");
selectSliceButton.onClick = function() {
var selectedFolder = Folder.selectDialog("选择切片裁片文件夹");
if (selectedFolder != null) {
slicePathEditText.text = selectedFolder.fsName;
// 可以在这里执行切片裁片相关的操作
}
};
// 大货裁片名称面板
var fileNamesPanel = dialog.add("panel", undefined, "大货裁片名称数量");
fileNamesPanel.orientation = "column";
fileNamesPanel.alignChildren = ["left","top"];
fileNamesPanel.spacing = 10;
fileNamesPanel.margins = 10;
// 存储文件名和输入框内容的数组
var userInputData = [];
// 更新文件名和输入框显示
function updateFileNames(folder) {
// 移除之前的所有元素
for (var i = fileNamesPanel.children.length - 1; i >= 0; i--) {
fileNamesPanel.children[i].remove();
}
// 清空数组
userInputData = [];
var files = folder.getFiles();
for (var i = 0; i < files.length; i++) {
// 使用正则表达式提取文件名(去掉路径和后缀)
完整文件路径=files[i].fsName
var fileName = new File(files[i]).name.replace(/\.\w+$/, "");
// 创建新的静态文本框
var fileNameStaticText = fileNamesPanel.add('statictext', undefined, fileName);
fileNameStaticText.preferredSize.width = 200;
// 创建新的输入框
var inputEditText = fileNamesPanel.add('edittext', undefined, '');
inputEditText.preferredSize.width = 100;
// 存储文件名和输入框内容
userInputData.push({
fileName: fileName,
inputText: ''
});
}
// 重新绘制对话框
dialog.layout.layout(true);
dialog.layout.resize();
}
// OK 和 Cancel 按钮
var buttonsGroup = dialog.add("group");
buttonsGroup.orientation = "row";
buttonsGroup.alignChildren = ["fill","top"];
buttonsGroup.spacing = 10;
buttonsGroup.margins = 0;
var okButton = buttonsGroup.add("button", undefined, "执行");
okButton.onClick = function() {
// 在这里执行 OK 按钮的操作
updateUserData();
alertUserInput();
dialog.close();
};
var cancelButton = buttonsGroup.add("button", undefined, "取消");
cancelButton.onClick = function() {
// 在这里执行 Cancel 按钮的操作
dialog.close();
};
// 显示对话框
dialog.show();
// 更新用户输入数据
function updateUserData() {
for (var i = 1; i < fileNamesPanel.children.length; i += 2) {
userInputData[(i - 1) / 2].inputText = fileNamesPanel.children[i].text;
}
}
// 弹出用户输入的内容
function alertUserInput() {
var userInput = "";
for (var i = 0; i < userInputData.length; i++) {
var 文件路径=templatePathEditText.text
var 文件名=userInputData[i].fileName
var 完整文件路径=文件路径+"/"+文件名+".tif"
// alert( 完整文件路径)
var 文件数量= userInputData[i].inputText
var 文件夹路径=slicePathEditText.text
var 文件对象 = new File(完整文件路径);
if (文件对象.exists) {
app.open(文件对象);
} else {
//alert("文件不存在:" + 完整文件路径);
}
更换当前文档裁片组外链(文件夹路径)
图层选择()
activeDocument.activeLayer.textItem.contents=文件数量
选择裁片图层()
合并图层()
另存为(文件夹路径)
activeDocument.close(SaveOptions.DONOTSAVECHANGES);
}
}
alert("换图完成,请检查好文件进行打印大货!!!",dialog.text+"----关于");
dialog.close();
function 另存为(文件夹路径)
{
文档名称=activeDocument.name.replace(/(?:\.[^.]*$|$)/, '');
saveIn=File(文件夹路径+ "/"+文档名称);
tifSaveOpt = new TiffSaveOptions();
tifSaveOpt.imageCompression = TIFFEncoding.TIFFLZW;
tifSaveOpt.byteOrder = ByteOrder.IBM;
asCopy=true
app.activeDocument.saveAs(saveIn,tifSaveOpt,asCopy);
}
function 选择裁片图层() //
{
try {
var d = new ActionDescriptor();
var r = new ActionReference();
r.putName(stringIDToTypeID("layer"), "裁片");
d.putReference(stringIDToTypeID("null"), r);
d.putBoolean(stringIDToTypeID("makeVisible"), false);
var list = new ActionList();
list.putInteger(74);
d.putList(stringIDToTypeID("layerID"), list);
executeAction(stringIDToTypeID("select"), d, DialogModes.NO);
}
catch (e) {
alert("找不到裁片图层",dialog.text+"----关于");
}
}
function 合并图层() //合并图层
{
var d = new ActionDescriptor();
executeAction(stringIDToTypeID("mergeLayersNew"), d, DialogModes.NO);
}
function 更换当前文档裁片组外链(文件夹路径)
{
try
{
裁片组 = app.activeDocument.layerSets.getByName("裁片").layers;
}
catch(e)
{
alert("找不到裁片组",dialog.text+"----提示");
}
for(var i=0;i<裁片组.length;i++)
{
裁片 = 裁片组[i];
app.activeDocument.activeLayer = 裁片;
if(裁片.kind == LayerKind.SMARTOBJECT)
{
更换链接智能对象路径(文件夹路径);
}
}
}
function 更换链接智能对象路径(文件夹路径)
{
//获取当前图层外链的智能对象路径
//先获取链接的文件名
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
//~ r.putName(charIDToTypeID("Lyr "), "◆左袖口"); //按名称查找
descLayer = executeActionGet(r);
res = descLayer.getObjectValue(stringIDToTypeID("smartObject"));
链接文件名 = res.getString(stringIDToTypeID("fileReference"));
//$.writeln(链接文件名);
//~ 链接文件路径 = res.getPath(stringIDToTypeID("link"));
//~ $.writeln(链接文件路径);
图片路径 = 文件夹路径 + "/" + 链接文件名;
var d = new ActionDescriptor();
d.putPath(stringIDToTypeID("null"), new File(图片路径));
executeAction(stringIDToTypeID("placedLayerRelinkToFile"), d, DialogModes.NO);
}
function 图层选择() //
{
try {
var d = new ActionDescriptor();
var r = new ActionReference();
r.putName(stringIDToTypeID("layer"), "数量");
d.putReference(stringIDToTypeID("null"), r);
d.putBoolean(stringIDToTypeID("makeVisible"), false);
var list = new ActionList();
list.putInteger(74);
d.putList(stringIDToTypeID("layerID"), list);
executeAction(stringIDToTypeID("select"), d, DialogModes.NO);
}
catch (e) {
alert("找不到数量图层",dialog.text+"----关于");
}
}
}
"""

View File

@@ -0,0 +1,166 @@
dxf19_jscode = """
// 文件夹路径
function 裁片抓取新的() {
app.activeDocument.suspendHistory("裁片抓取", "置入对象()");
}
function 置入对象() {
var folderPath = "D:/MarkTemp/Pdfmarktemp";
var folder = new Folder(folderPath);
// 获取文件夹中的文件
var files = folder.getFiles();
// 新建一个数组来存储文件名称
var fileNamesArray = [];
for (var i = 0; i < files.length; i++) {
if (files[i] instanceof File) {
var doc = app.activeDocument;
var fileName = files[i].name;
var newDocumentName = fileName.replace(/\.pdf$/, '');
var modifiedString = newDocumentName.replace(/-\d+_\d+/, '');
var newmodifiedString = modifiedString.split("-");
// 检查是否存在相同的文件名
var duplicate = false;
for (var j = 0; j < fileNamesArray.length; j++) {
if (fileNamesArray[j] === modifiedString) {
duplicate = true;
break;
}
}
if (duplicate) {
$.writeln("文件名重复,跳过: " + fileName);
continue;
}
// 将新的文档名添加到文件名数组中
fileNamesArray.push(modifiedString);
$.writeln("文档名称: " + fileName);
var 文件路径 = folderPath + "/" + fileName;
// 调用你的函数
var match = newDocumentName.match(/_(\d+)/);
var 角度信息 = match ? match[1] : "";
if (角度信息 === "180" || 角度信息 === "-180") {
置入对象180度(文件路径);
} else {
// 如果角度信息不是 "180""-180",执行默认逻辑
置入对象0度(文件路径);
}
var extractedPart = newmodifiedString[0];
var 大货裁片组名 = extractedPart + "-大货裁片";
// var 当前花样图层 = app.activeDocument.layers.getByName(newDocumentName);
// app.activeDocument.activeLayer = 当前花样图层;
var 大货裁片组;
try {
大货裁片组 = app.activeDocument.layerSets.getByName(大货裁片组名);
} catch (e) {
大货裁片组 = app.activeDocument.layerSets.add();
大货裁片组.name = 大货裁片组名;
}
// 将当前图层移动到大货裁片图层组内
app.activeDocument.activeLayer.move(大货裁片组, ElementPlacement.INSIDE);
栅格化图层智能对象();
// modifiedString = fileName.replace(/-\d+_\d+/, '');
app.activeDocument.activeLayer.name = modifiedString;
}
}
}
function 栅格化图层智能对象() {
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
executeAction(stringIDToTypeID("rasterizeLayer"), d, DialogModes.NO);
}
function 栅格化图层智能对象() //栅格化图层
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
executeAction(stringIDToTypeID("rasterizeLayer"), d, DialogModes.NO);
}
function 置入对象0度(文件路径)
{
var d = new ActionDescriptor();
var d1 = new ActionDescriptor();
d1.putEnumerated(stringIDToTypeID("selection"), stringIDToTypeID("pdfSelection"), stringIDToTypeID("page"));
d1.putInteger(stringIDToTypeID("pageNumber"), 1);
d1.putEnumerated(stringIDToTypeID("crop"), stringIDToTypeID("cropTo"), stringIDToTypeID("boundingBox"));
d1.putBoolean(stringIDToTypeID("suppressWarnings"), false);
d1.putBoolean(stringIDToTypeID("antiAlias"), true);
d1.putBoolean(stringIDToTypeID("clippingPath"), true);
d.putObject(stringIDToTypeID("as"), stringIDToTypeID("PDFGenericFormat"), d1);
d.putInteger(stringIDToTypeID("ID"), 4);
d.putPath(stringIDToTypeID("null"), new File(文件路径));
d.putEnumerated(stringIDToTypeID("freeTransformCenterState"), stringIDToTypeID("quadCenterState"), stringIDToTypeID("QCSAverage"));
var d2 = new ActionDescriptor();
d2.putUnitDouble(stringIDToTypeID("horizontal"), stringIDToTypeID("distanceUnit"), 0);
d2.putUnitDouble(stringIDToTypeID("vertical"), stringIDToTypeID("distanceUnit"), 0);
d.putObject(stringIDToTypeID("offset"), stringIDToTypeID("offset"), d2);
//d.putUnitDouble(stringIDToTypeID("width"), stringIDToTypeID("percentUnit"), -100);
// d.putUnitDouble(stringIDToTypeID("height"), stringIDToTypeID("percentUnit"), -100);
d.putBoolean(stringIDToTypeID("antiAlias"), false);
executeAction(stringIDToTypeID("placeEvent"), d, DialogModes.NO);
}
function 置入对象180度(文件路径)
{
var d = new ActionDescriptor();
var d1 = new ActionDescriptor();
d1.putEnumerated(stringIDToTypeID("selection"), stringIDToTypeID("pdfSelection"), stringIDToTypeID("page"));
d1.putInteger(stringIDToTypeID("pageNumber"), 1);
d1.putEnumerated(stringIDToTypeID("crop"), stringIDToTypeID("cropTo"), stringIDToTypeID("boundingBox"));
d1.putBoolean(stringIDToTypeID("suppressWarnings"), false);
d1.putBoolean(stringIDToTypeID("antiAlias"), true);
d1.putBoolean(stringIDToTypeID("clippingPath"), true);
d.putObject(stringIDToTypeID("as"), stringIDToTypeID("PDFGenericFormat"), d1);
d.putInteger(stringIDToTypeID("ID"), 4);
d.putPath(stringIDToTypeID("null"), new File(文件路径));
d.putEnumerated(stringIDToTypeID("freeTransformCenterState"), stringIDToTypeID("quadCenterState"), stringIDToTypeID("QCSAverage"));
var d2 = new ActionDescriptor();
d2.putUnitDouble(stringIDToTypeID("horizontal"), stringIDToTypeID("distanceUnit"), 0);
d2.putUnitDouble(stringIDToTypeID("vertical"), stringIDToTypeID("distanceUnit"), 0);
d.putObject(stringIDToTypeID("offset"), stringIDToTypeID("offset"), d2);
d.putUnitDouble(stringIDToTypeID("width"), stringIDToTypeID("percentUnit"), -100);
d.putUnitDouble(stringIDToTypeID("height"), stringIDToTypeID("percentUnit"), -100);
d.putBoolean(stringIDToTypeID("antiAlias"), false);
executeAction(stringIDToTypeID("placeEvent"), d, DialogModes.NO);
}
"""

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,136 @@
dxf20_jscode = """
function 混排通码延申导出() {
var 主文档 = app.activeDocument;
var 主文档路径 = 主文档.path;
var 新文件夹 = (主文档路径 + "/小片裁片"); // 在桌面上创建一个名为"导出目录"的文件夹
var 导出目录 = Folder(新文件夹);
if (!导出目录.exists) {
导出目录.create();
}
var doc = app.activeDocument;
// 获取所有图层
var layers = doc.layers;
// 存储符合条件的图层组
var matchingLayerSets = [];
// 遍历每个图层
for (var i = 0; i < layers.length; i++) {
var layer = layers[i];
// 如果是图层组,检查名称是否包含 "大货裁片"
if (layer.typename == "LayerSet" && layer.name.indexOf("大货裁片") !== -1) {
matchingLayerSets.push(layer);
// 输出图层组名称
$.writeln("图层组名称:" + layer.name);
图层组名称=layer.name
// 输出图层组内子图层的名称
for (var j = 0; j < layer.layers.length; j++) {
var subLayer = layer.layers[j];
$.writeln(" 子图层名称:" + subLayer.name);
子图层名称=subLayer.name
子图层名称分割=子图层名称.split("-")
素材图名称=子图层名称分割[0]
空白裁片模板 = app.activeDocument.layerSets.getByName(图层组名称).layers.getByName(子图层名称);
app.activeDocument.activeLayer = 空白裁片模板;
载入选区()
素材名称 = app.activeDocument.layers.getByName(素材图名称);
app.activeDocument.activeLayer = 素材名称;
添加图层蒙版()
新建文档()
当前花样图层 = app.activeDocument.activeLayer
app.activeDocument.crop( 当前花样图层.bounds, 0);
var 文件路径 = 导出目录 + "/" + 子图层名称 + ".tif";
tiffOptions = new TiffSaveOptions();
app.activeDocument.saveAs(new File(文件路径), tiffOptions);
app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
app.activeDocument=doc
历史记录回退3()
}
}
}
// 输出符合条件的图层组数量
//$.writeln("符合条件的图层组数量:" + matchingLayerSets.length);
}
function 载入选区() //载入选区
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("channel"), stringIDToTypeID("selection"));
d.putReference(stringIDToTypeID("null"), r);
var r1 = new ActionReference();
r1.putEnumerated(stringIDToTypeID("channel"), stringIDToTypeID("channel"), stringIDToTypeID("transparencyEnum"));
d.putReference(stringIDToTypeID("to"), r1);
executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
}
function 添加图层蒙版() //添加图层蒙版
{
var d = new ActionDescriptor();
d.putClass(stringIDToTypeID("new"), stringIDToTypeID("channel"));
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("channel"), stringIDToTypeID("channel"), stringIDToTypeID("mask"));
d.putReference(stringIDToTypeID("at"), r);
d.putEnumerated(stringIDToTypeID("using"), stringIDToTypeID("userMaskEnabled"), stringIDToTypeID("revealSelection"));
executeAction(stringIDToTypeID("make"), d, DialogModes.NO);
}
function 新建文档() //复制图层
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putClass(stringIDToTypeID("document"));
d.putReference(stringIDToTypeID("null"), r);
var r1 = new ActionReference();
r1.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("using"), r1);
d.putInteger(stringIDToTypeID("version"), 5);
executeAction(stringIDToTypeID("make"), d, DialogModes.NO);
}
function 历史记录回退3() //
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putOffset(stringIDToTypeID("historyState"), -2);
d.putReference(stringIDToTypeID("null"), r);
executeAction(stringIDToTypeID("select"), d, DialogModes.NO);
}
"""

View File

@@ -0,0 +1,39 @@
dxf21_jscode = """
function 创建裁片排版文档(画布宽,画布高,分辨率,文档名称)
{
app.preferences.rulerUnits = Units.MM; //修改指定单位为毫米
app.documents.add(画布宽, 画布高,分辨率, 文档名称, NewDocumentMode.CMYK);
}
function 置入链接的智能对象(dir, DXFname) {
图片路径 = dir + "/" + DXFname + ".tif"
var d = new ActionDescriptor();
d.putInteger(stringIDToTypeID("ID"), 16);
d.putPath(stringIDToTypeID("null"), new File(图片路径));
d.putBoolean(stringIDToTypeID("linked"), true);
d.putEnumerated(stringIDToTypeID("freeTransformCenterState"), stringIDToTypeID("quadCenterState"), stringIDToTypeID("QCSAverage"));
var d1 = new ActionDescriptor();
executeAction(stringIDToTypeID("placeEvent"), d, DialogModes.NO);
}
function 裁片排版_lay(中心x_mm, 中心y_mm) {
ps中心x_mm = 中心x_mm;
ps中心y_mm = 中心y_mm;
alb = app.activeDocument.activeLayer.bounds;
当前x = (alb[0] + alb[2]) / 2; //mm数
当前y = (alb[1] + alb[3]) / 2; //mm数
app.activeDocument.activeLayer.translate(ps中心x_mm - Number(当前x), ps中心y_mm - Number(当前y)); //全局单位设置为mm即可
}
function 裁片角度(角度) {
app.activeDocument.activeLayer.rotate(角度);
//app.refresh()
}
"""

View File

@@ -0,0 +1,453 @@
dxf22_jscode = """
//PS智能对象换图
function 模特换衣功能(){
var dialog = new Window("dialog");
dialog.text = "模特批量替换";
dialog.preferredSize.width = 400;
dialog.preferredSize.height = 150;
dialog.orientation = "column";
dialog.alignChildren = ["center","top"];
dialog.spacing = 10;
dialog.margins = 16;
// GROUP1
// ======
var group1 = dialog.add("group");
group1.orientation = "row";
group1.alignChildren = ["left","center"];
group1.spacing = 10;
group1.margins = 0;
var statictext1 = group1.add("statictext");
statictext1.text = "模板文件";
statictext1.justify = "center";
var edittext1 = group1.add("edittext");
edittext1.preferredSize.width = 250;
var button1 = group1.add("button");
button1.text = "选择文件";
button1.justify = "center";
// GROUP2
// ======
var group2 = dialog.add("group");
group2.orientation = "row";
group2.alignChildren = ["left","center"];
group2.spacing = 10;
group2.margins = 0;
var statictext2 = group2.add("statictext");
statictext2.text = "素材目录";
statictext2.justify = "center";
var edittext2 = group2.add("edittext");
edittext2.preferredSize.width = 250;
var button2 = group2.add("button");
button2.text = "选择目录";
button2.justify = "center";
// GROUP3
// ======
var group3 = dialog.add("group");
group3.orientation = "row";
group3.alignChildren = ["left","center"];
group3.spacing = 10;
group3.margins = 0;
var statictext3 = group3.add("statictext");
statictext3.text = "导出目录";
statictext3.justify = "center";
var edittext3 = group3.add("edittext");
edittext3.preferredSize.width = 250;
var button3 = group3.add("button");
button3.text = "选择目录";
button3.justify = "center";
var group5 = dialog.add("group");
var cbox1 = group5.add("checkbox");
cbox1.text = "是否遍历子文件夹素材";
cbox1.value = true;
var cbox2 = group5.add("checkbox");
cbox2.text = "是否保存文件结构";
cbox2.value = true;
var cbox3 = group5.add("checkbox");
cbox3.text = "切片导出";
cbox3.value = false;
// GROUP4
// ======
var group4 = dialog.add("group");
group4.orientation = "row";
group4.alignChildren = ["left","center"];
group4.spacing = 10;
group4.margins = 0;
var button4 = group4.add("button");
button4.text = "执行";
button4.justify = "center";
var button5 = group4.add("button");
button5.text = "退出";
button5.justify = "center";
button1.onClick = function()
{
var inputFile= app.openDialog();
if (inputFile != null)
{
edittext1.text = decodeURI(inputFile);
}
}
button2.onClick = function()
{
var inputFolder = Folder.selectDialog("请选择素材目录:");
if (inputFolder != null)
{
edittext2.text = decodeURI(inputFolder);
}
}
button3.onClick = function()
{
var inputFolder = Folder.selectDialog("请选择导出目录:");
if (inputFolder != null)
{
edittext3.text = decodeURI(inputFolder);
}
}
button4.onClick = function()
{
模板路径 = edittext1.text;
素材目录 = edittext2.text;
导出目录 = edittext3.text;
main(模板路径,素材目录,导出目录);
}
button5.onClick = function()
{
dialog.close();
}
function main(模板路径,素材目录,导出目录)
{
if(Folder(导出目录).exists==false){Folder(导出目录).create();}
var doc = app.open(File(模板路径));
//~ 素材文件列表 = Folder(素材目录).getFiles("*.psd");
isSubFolders = cbox1.value;
素材文件列表 = 遍历目录指定类型文件(素材目录,isSubFolders);
alert("当前目录一共有"+素材文件列表.length+"个素材。","提示:");
try
{
lay_替换对象图层名 = "替换对象";
lay_替换对象 = app.activeDocument.artLayers.getByName(lay_替换对象图层名);
}
catch(e)
{
alert("未找到["+lay_替换对象图层名+"]智能对象图层!","提示:");
}
app.activeDocument.activeLayer = lay_替换对象;
for(var i=0;i<素材文件列表.length;i++)
{
scpsd_path = 素材文件列表[i];
//~ lay_替换对象.visible = false;
素材名 = decodeURI(File(scpsd_path).name.replace(/(?:\.[^.]*$|$)/, ''));
//替换内容
var d = new ActionDescriptor();
d.putPath(stringIDToTypeID("null"), new File(scpsd_path));
executeAction(stringIDToTypeID("placedLayerReplaceContents"), d, DialogModes.NO);
if(cbox2.value) //保持结构
{
结构导出目录 = 导出目录+"/" + getRelativePath(decodeURI(File(scpsd_path).path), 素材目录);
if(Folder(结构导出目录).exists==false){Folder(结构导出目录).create();}
保存路径 = 结构导出目录+"/"+素材名+".jpg";
$.writeln(保存路径);
if(cbox3.value) //按切片
{
//~ 按切片导出图片(结构导出目录,app.activeDocument.name.replace(/(?:\.[^.]*$|$)/, ''));
按切片导出图片(结构导出目录,素材名);
}
else
{
保存JPG(保存路径);
}
}
else
{
if(cbox3.value) //按切片
{
//~ 按切片导出图片(导出目录,app.activeDocument.name.replace(/(?:\.[^.]*$|$)/, ''));
按切片导出图片(导出目录,素材名);
}
else
{
保存JPG(导出目录+"/"+素材名+".jpg");
}
}
}
doc.close(SaveOptions.DONOTSAVECHANGES);
alert("处理完成!","提示:");
}
function getRelativePath(targetPath, basePath)
{
var targetFile = new File(targetPath);
var baseFolder = new Folder(basePath);
var relativePath = targetFile.getRelativeURI(baseFolder);
return decodeURI(relativePath); // 解码 URI 编码的路径
}
function 保存JPG(jpg_save_path)
{
// 以JPEG格式保存输出
var jpegOptions = new JPEGSaveOptions();
// 将jpeg质量设置得很低使文件很小
jpegOptions.quality = 12;
app.activeDocument.saveAs(new File(jpg_save_path), jpegOptions,true);
}
function 遍历目录指定类型文件(inputFolder,isSubFolders)
{
if(isSubFolders==undefined)
{
isSubFolders = true;
}
all_files_list = [];
if (inputFolder != null) {
filesArray = scanFolder(inputFolder);
if (filesArray.length > 0)
{
for (i = 0;i<filesArray.length;i++)
{
all_files_list.push(filesArray[i]);
}
}
}
return all_files_list;
function scanFolder(folder)
{
var filesArray = [],
fileList = Folder(folder).getFiles();
var file;
for (var i = 0; i < fileList.length; i++) {
file = fileList[i];
if (file instanceof Folder)
{
if(isSubFolders==false)
{
continue;
}
else
{
filesArray = filesArray.concat(scanFolder(file));
}
}
else if (file instanceof File && file.name.match(/\.(jpg|tif|psd|png|)$/i))
{
filesArray.push(file);
}
}
return filesArray;
}
}
function 按切片导出图片(保存路径,替换词)
{
//~ alert(保存路径);
var d = new ActionDescriptor();
var d1 = new ActionDescriptor();
d1.putEnumerated(charIDToTypeID("Op "), charIDToTypeID("SWOp"), charIDToTypeID("OpSa"));
d1.putBoolean(charIDToTypeID("DIDr"), true);
d1.putPath(stringIDToTypeID("in"), new File(保存路径));
d1.putString(charIDToTypeID("ovFN"), 替换词+".jpg");
d1.putEnumerated(stringIDToTypeID("format"), charIDToTypeID("IRFm"), stringIDToTypeID("JPEG"));
d1.putBoolean(charIDToTypeID("Intr"), false);
d1.putInteger(stringIDToTypeID("quality"), 80);
d1.putInteger(charIDToTypeID("QChS"), 0);
d1.putInteger(charIDToTypeID("QCUI"), 0);
d1.putBoolean(charIDToTypeID("QChT"), false);
d1.putBoolean(charIDToTypeID("QChV"), false);
d1.putBoolean(stringIDToTypeID("optimized"), true);
d1.putInteger(charIDToTypeID("Pass"), 1);
d1.putDouble(stringIDToTypeID("blur"), 0);
d1.putBoolean(charIDToTypeID("Mtt "), true);
d1.putBoolean(charIDToTypeID("EICC"), false);
d1.putInteger(charIDToTypeID("MttR"), 255);
d1.putInteger(charIDToTypeID("MttG"), 255);
d1.putInteger(charIDToTypeID("MttB"), 255);
d1.putBoolean(charIDToTypeID("SHTM"), false);
d1.putBoolean(charIDToTypeID("SImg"), true);
d1.putEnumerated(charIDToTypeID("SWsl"), charIDToTypeID("STsl"), charIDToTypeID("SLAl"));
d1.putEnumerated(charIDToTypeID("SWch"), charIDToTypeID("STch"), charIDToTypeID("CHDc"));
d1.putEnumerated(charIDToTypeID("SWmd"), charIDToTypeID("STmd"), charIDToTypeID("MDCC"));
d1.putBoolean(charIDToTypeID("ohXH"), false);
d1.putBoolean(charIDToTypeID("ohIC"), true);
d1.putBoolean(charIDToTypeID("ohAA"), true);
d1.putBoolean(charIDToTypeID("ohQA"), true);
d1.putBoolean(charIDToTypeID("ohCA"), false);
d1.putBoolean(charIDToTypeID("ohIZ"), true);
d1.putEnumerated(charIDToTypeID("ohTC"), charIDToTypeID("SToc"), charIDToTypeID("OC03"));
d1.putEnumerated(charIDToTypeID("ohAC"), charIDToTypeID("SToc"), charIDToTypeID("OC03"));
d1.putInteger(charIDToTypeID("ohIn"), -1);
d1.putEnumerated(charIDToTypeID("ohLE"), charIDToTypeID("STle"), charIDToTypeID("LE03"));
d1.putEnumerated(charIDToTypeID("ohEn"), charIDToTypeID("STen"), charIDToTypeID("EN00"));
d1.putBoolean(charIDToTypeID("olCS"), false);
d1.putEnumerated(charIDToTypeID("olEC"), charIDToTypeID("STst"), charIDToTypeID("ST00"));
d1.putEnumerated(charIDToTypeID("olWH"), charIDToTypeID("STwh"), charIDToTypeID("WH01"));
d1.putEnumerated(charIDToTypeID("olSV"), charIDToTypeID("STsp"), charIDToTypeID("SP04"));
d1.putEnumerated(charIDToTypeID("olSH"), charIDToTypeID("STsp"), charIDToTypeID("SP04"));
var list = new ActionList();
var d2 = new ActionDescriptor();
d2.putEnumerated(charIDToTypeID("ncTp"), charIDToTypeID("STnc"), charIDToTypeID("NC00"));
list.putObject(charIDToTypeID("SCnc"), d2);
var d3 = new ActionDescriptor();
d3.putEnumerated(charIDToTypeID("ncTp"), charIDToTypeID("STnc"), charIDToTypeID("NC19"));
list.putObject(charIDToTypeID("SCnc"), d3);
var d4 = new ActionDescriptor();
d4.putEnumerated(charIDToTypeID("ncTp"), charIDToTypeID("STnc"), charIDToTypeID("NC28"));
list.putObject(charIDToTypeID("SCnc"), d4);
var d5 = new ActionDescriptor();
d5.putEnumerated(charIDToTypeID("ncTp"), charIDToTypeID("STnc"), charIDToTypeID("NC24"));
list.putObject(charIDToTypeID("SCnc"), d5);
var d6 = new ActionDescriptor();
d6.putEnumerated(charIDToTypeID("ncTp"), charIDToTypeID("STnc"), charIDToTypeID("NC24"));
list.putObject(charIDToTypeID("SCnc"), d6);
var d7 = new ActionDescriptor();
d7.putEnumerated(charIDToTypeID("ncTp"), charIDToTypeID("STnc"), charIDToTypeID("NC24"));
list.putObject(charIDToTypeID("SCnc"), d7);
d1.putList(charIDToTypeID("olNC"), list);
d1.putBoolean(charIDToTypeID("obIA"), false);
d1.putString(charIDToTypeID("obIP"), "");
d1.putEnumerated(charIDToTypeID("obCS"), charIDToTypeID("STcs"), charIDToTypeID("CS01"));
var list1 = new ActionList();
var d8 = new ActionDescriptor();
d8.putEnumerated(charIDToTypeID("ncTp"), charIDToTypeID("STnc"), charIDToTypeID("NC01"));
list1.putObject(charIDToTypeID("SCnc"), d8);
var d9 = new ActionDescriptor();
d9.putEnumerated(charIDToTypeID("ncTp"), charIDToTypeID("STnc"), charIDToTypeID("NC20"));
list1.putObject(charIDToTypeID("SCnc"), d9);
var d10 = new ActionDescriptor();
d10.putEnumerated(charIDToTypeID("ncTp"), charIDToTypeID("STnc"), charIDToTypeID("NC02"));
list1.putObject(charIDToTypeID("SCnc"), d10);
var d11 = new ActionDescriptor();
d11.putEnumerated(charIDToTypeID("ncTp"), charIDToTypeID("STnc"), charIDToTypeID("NC19"));
list1.putObject(charIDToTypeID("SCnc"), d11);
var d12 = new ActionDescriptor();
d12.putEnumerated(charIDToTypeID("ncTp"), charIDToTypeID("STnc"), charIDToTypeID("NC06"));
list1.putObject(charIDToTypeID("SCnc"), d12);
var d13 = new ActionDescriptor();
d13.putEnumerated(charIDToTypeID("ncTp"), charIDToTypeID("STnc"), charIDToTypeID("NC24"));
list1.putObject(charIDToTypeID("SCnc"), d13);
var d14 = new ActionDescriptor();
d14.putEnumerated(charIDToTypeID("ncTp"), charIDToTypeID("STnc"), charIDToTypeID("NC24"));
list1.putObject(charIDToTypeID("SCnc"), d14);
var d15 = new ActionDescriptor();
d15.putEnumerated(charIDToTypeID("ncTp"), charIDToTypeID("STnc"), charIDToTypeID("NC24"));
list1.putObject(charIDToTypeID("SCnc"), d15);
var d16 = new ActionDescriptor();
d16.putEnumerated(charIDToTypeID("ncTp"), charIDToTypeID("STnc"), charIDToTypeID("NC22"));
list1.putObject(charIDToTypeID("SCnc"), d16);
d1.putList(charIDToTypeID("ovNC"), list1);
d1.putBoolean(charIDToTypeID("ovCM"), false);
d1.putBoolean(charIDToTypeID("ovCW"), true);
d1.putBoolean(charIDToTypeID("ovCU"), true);
d1.putBoolean(charIDToTypeID("ovSF"), true);
d1.putBoolean(charIDToTypeID("ovCB"), true);
d.putObject(stringIDToTypeID("using"), stringIDToTypeID("SaveForWeb"), d1);
executeAction(stringIDToTypeID("export"), d, DialogModes.NO);
}
dialog.show();
}
"""

View File

@@ -0,0 +1,474 @@
dxf23_jscode = """
function 自动连晒(){
var dialog = new Window("dialog");
dialog.text = "S/O样自动连晒";
//dialog.text = "SO自动米样拼贴";
dialog.orientation = "row";
dialog.alignChildren = ["left","top"];
dialog.spacing = 10;
dialog.margins = 16;
// GROUP1
// ======
var group1 = dialog.add("group", undefined, {name: "group1"});
group1.orientation = "column";
group1.alignChildren = ["fill","top"];
group1.spacing = 10;
group1.margins = 0;
// PANEL1
// ======
var panel1 = group1.add("panel", undefined, undefined, {name: "panel1"});
panel1.text = "源图像";
panel1.preferredSize.width = 388;
panel1.preferredSize.height = 205;
panel1.orientation = "column";
panel1.alignChildren = ["left","top"];
panel1.spacing = 10;
panel1.margins = 10;
var statictext1 = panel1.add("statictext", undefined, undefined, {name: "statictext1"});
statictext1.text = "使用:";
// GROUP2
// ======
var group2 = panel1.add("group", undefined, {name: "group2"});
group2.orientation = "row";
group2.alignChildren = ["left","center"];
group2.spacing = 10;
group2.margins = 0;
var button1 = group2.add("button", undefined, undefined, {name: "button1"});
button1.text = "选取";
var edittext1 = group2.add('edittext {properties: {name: "edittext1"}}');
edittext1.text = "[选择图像文件夹]";
edittext1.preferredSize.width = 300;
// PANEL2
// ======
var panel2 = group1.add("panel", undefined, undefined, {name: "panel2"});
panel2.text = "SO小样文档";
panel2.preferredSize.height = 160;
panel2.orientation = "column";
panel2.alignChildren = ["left","top"];
panel2.spacing = 10;
panel2.margins = 10;
var statictext2 = panel2.add("statictext", undefined, undefined, {name: "statictext2"});
statictext2.text = "设定:";
// GROUP3
// ======
var group3 = panel2.add("group", undefined, {name: "group3"});
group3.orientation = "row";
group3.alignChildren = ["left","center"];
group3.spacing = 10;
group3.margins = 0;
var statictext3 = group3.add("statictext", undefined, undefined, {name: "statictext3"});
statictext3.text = "宽度(cm):";
var edittext2 = group3.add('edittext {properties: {name: "edittext2"}}');
edittext2.preferredSize.width = 100;
var statictext4 = group3.add("statictext", undefined, undefined, {name: "statictext4"});
statictext4.text = "高度(cm):";
var edittext3 = group3.add('edittext {properties: {name: "edittext3"}}');
edittext3.preferredSize.width = 100;
// GROUP4
// ======
var group4 = panel2.add("group", undefined, {name: "group4"});
group4.orientation = "row";
group4.alignChildren = ["left","center"];
group4.spacing = 10;
group4.margins = 0;
// GROUP5
// ======
var group5 = group1.add("group", undefined, {name: "group5"});
group5.orientation = "row";
group5.alignChildren = ["left","center"];
group5.spacing = 10;
group5.margins = 0;
// PANEL3
// ======
// GROUP7
// ======
var group7 = dialog.add("group", undefined, {name: "group7"});
group7.orientation = "column";
group7.alignChildren = ["fill","top"];
group7.spacing = 10;
group7.margins = 0;
var ok = group7.add("button", undefined, undefined, {name: "ok"});
ok.text = "确认";
var cancel = group7.add("button", undefined, undefined, {name: "cancel"});
cancel.text = "取消";
button1.onClick = function () {
// 打开文件夹选择对话框
var selectedFolder = Folder.selectDialog("选择图像文件夹");
// 检查用户是否取消了选择
if (selectedFolder) {
// 将选择的文件夹路径显示在输入框中
edittext1.text = selectedFolder.fsName;
}
};
ok.onClick = function () {
app.preferences.rulerUnits = Units.PIXELS;
var 素材图片文件夹 = new Folder(edittext1.text);
var 遍历tiff = 素材图片文件夹.getFiles("*.*");
// 新建文件夹
var 新文件夹 = new Folder(edittext1.text + "/SO小样拼贴");
新文件夹.create();
var 新加字文件夹 = new Folder(edittext1.text + "/SO小样拼贴加字");
新加字文件夹.create();
宽度=Number (edittext2.text);
高度=Number (edittext3.text);
for (var i = 0; i < 遍历tiff.length; i++) {
if (遍历tiff[i] instanceof File) {
app.open(遍历tiff[i]);
app.activeDocument.flatten();
var 当前文档 = app.activeDocument;
var 当前文档名称 = 当前文档.name;
图像大小()
预设图案(当前文档名称);
app.activeDocument.crop([UnitValue("0px"), UnitValue("0px"), UnitValue(宽度, "cm"), UnitValue(高度, "cm")]);
填充图案(当前文档名称);
app.activeDocument.flatten();
画布扩展()
// 保存新的图像文件到新建的文件夹中
var 保存路径 = 新文件夹 + "/" + 当前文档名称;
var tifSaveOpt = new TiffSaveOptions();
tifSaveOpt.imageCompression = TIFFEncoding.TIFFLZW;
tifSaveOpt.byteOrder = ByteOrder.IBM;
var asCopy = true;
app.activeDocument.saveAs(new File(保存路径), tifSaveOpt, asCopy);
创建并处理文本图层();
app.activeDocument.flatten();
var 保存路径 = 新加字文件夹 + "/" + 当前文档名称;
var tifSaveOpt = new TiffSaveOptions();
tifSaveOpt.imageCompression = TIFFEncoding.TIFFLZW;
tifSaveOpt.byteOrder = ByteOrder.IBM;
var asCopy = true;
app.activeDocument.saveAs(new File(保存路径), tifSaveOpt, asCopy);
app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
}
}
//alert("小样连晒完成")
dialog.close();
// 创建并保存拼贴图像(新文件夹, 幅宽)
};
function 预设图案(当前文档名称) //
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putClass(stringIDToTypeID("pattern"));
d.putReference(stringIDToTypeID("null"), r);
var r1 = new ActionReference();
r1.putProperty(stringIDToTypeID("property"), stringIDToTypeID("selection"));
r1.putEnumerated(stringIDToTypeID("document"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("using"), r1);
d.putString(stringIDToTypeID("name"), 当前文档名称);
executeAction(stringIDToTypeID("make"), d, DialogModes.NO);
}
function 填充图案(当前文档名称) //
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putClass(stringIDToTypeID("contentLayer"));
d.putReference(stringIDToTypeID("null"), r);
var d1 = new ActionDescriptor();
var d2 = new ActionDescriptor();
var d3 = new ActionDescriptor();
d3.putString(stringIDToTypeID("name"), 当前文档名称);
d2.putObject(stringIDToTypeID("pattern"), stringIDToTypeID("pattern"), d3);
d1.putObject(stringIDToTypeID("type"), stringIDToTypeID("patternLayer"), d2);
d.putObject(stringIDToTypeID("using"), stringIDToTypeID("contentLayer"), d1);
executeAction(stringIDToTypeID("make"), d, DialogModes.NO);
}
function 图像大小() //图像大小
{
var d = new ActionDescriptor();
d.putUnitDouble(stringIDToTypeID("resolution"), stringIDToTypeID("densityUnit"), 200);
d.putBoolean(stringIDToTypeID("scaleStyles"), true);
d.putBoolean(stringIDToTypeID("constrainProportions"), true);
d.putEnumerated(charIDToTypeID("Intr"), stringIDToTypeID("interpolationType"), stringIDToTypeID("nearestNeighbor"));
executeAction(stringIDToTypeID("imageSize"), d, DialogModes.NO);
}
function 画布扩展() //
{
var d = new ActionDescriptor();
d.putBoolean(stringIDToTypeID("relative"), true);
d.putUnitDouble(stringIDToTypeID("width"), stringIDToTypeID("distanceUnit"), 14.4);
d.putUnitDouble(stringIDToTypeID("height"), stringIDToTypeID("distanceUnit"), 14.4);
d.putEnumerated(stringIDToTypeID("horizontal"), stringIDToTypeID("horizontalLocation"), stringIDToTypeID("center"));
d.putEnumerated(stringIDToTypeID("vertical"), stringIDToTypeID("verticalLocation"), stringIDToTypeID("center"));
d.putEnumerated(stringIDToTypeID("canvasExtensionColorType"), stringIDToTypeID("canvasExtensionColorType"), stringIDToTypeID("color"));
var d1 = new ActionDescriptor();
d1.putDouble(stringIDToTypeID("red"), 255);
d1.putDouble(stringIDToTypeID("green"), 255);
d1.putDouble(stringIDToTypeID("blue"), 255);
d.putObject(stringIDToTypeID("canvasExtensionColor"), stringIDToTypeID("RGBColor"), d1);
executeAction(stringIDToTypeID("canvasSize"), d, DialogModes.NO);
}
function 创建并处理文本图层() {
// 新建图层
var textLayer = activeDocument.artLayers.add();
// 将新建图层变成文本图层
textLayer.kind = LayerKind.TEXT;
// 将文本内容改为当前文档name
textLayer.textItem.contents = activeDocument.name;
// 字体大小固定值
var 固定字体大小 = 30; // 例如30像素
textLayer.textItem.size = 固定字体大小;
// 文字字体固定值
textLayer.textItem.font = "微软雅黑";
// 计算并调整文本位置
var x = activeDocument.width - textLayer.bounds[2];
var y = textLayer.bounds[1];
textLayer.translate(x, -y);
// 偏移
textLayer.translate(UnitValue("-1cm"), UnitValue("+0.5cm"));
// 复制并栅格化图层
var copyLayer = textLayer.duplicate();
copyLayer.rasterize(RasterizeType.ENTIRELAYER);
// 设置固定颜色值
var 固定颜色 = new SolidColor();
固定颜色.rgb.red = 255; // 红色分量
固定颜色.rgb.green = 255; // 绿色分量
固定颜色.rgb.blue = 255; // 蓝色分量
activeDocument.activeLayer = copyLayer;
activeDocument.selection.fill(固定颜色, ColorBlendMode.NORMAL, 100, true);
// 白边
activeDocument.activeLayer.applyMinimum(10);
后移一层()
向上选择()
向下合并()
名称更改字体()
缩小字体图层至文档一半()
多选背景()
底对齐()
水平居中对齐()
}
// 调用函数
function 后移一层() //
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
var r1 = new ActionReference();
r1.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("previous"));
d.putReference(stringIDToTypeID("to"), r1);
executeAction(stringIDToTypeID("move"), d, DialogModes.NO);
}
function 向上选择() //
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("forwardEnum"));
d.putReference(stringIDToTypeID("null"), r);
d.putBoolean(stringIDToTypeID("makeVisible"), false);
var list = new ActionList();
list.putInteger(19);
d.putList(stringIDToTypeID("layerID"), list);
executeAction(stringIDToTypeID("select"), d, DialogModes.NO);
}
function 向下合并() //向下合并
{
var d = new ActionDescriptor();
executeAction(stringIDToTypeID("mergeLayersNew"), d, DialogModes.NO);
}
function 名称更改字体() //名称更改
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
var d1 = new ActionDescriptor();
d1.putString(stringIDToTypeID("name"), "字体");
d.putObject(stringIDToTypeID("to"), stringIDToTypeID("layer"), d1);
executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
}
function 缩小字体图层至文档一半() {
var 文档 = app.activeDocument;
var 字体图层 = null;
// 遍历文档中的图层以找到名为"字体"的图层
for (var i = 0; i < 文档.artLayers.length; i++) {
if (文档.artLayers[i].name === "字体") {
字体图层 = 文档.artLayers[i];
break;
}
}
if (字体图层 !== null) {
// 获取文档的宽度的一半
var 目标宽度 = 文档.width / 2;
// 获取图层的当前宽度
var 图层宽度 = 字体图层.bounds[2] - 字体图层.bounds[0];
// 计算缩放比例
var 缩放比例 = 目标宽度 / 图层宽度 * 100;
// 缩放图层
字体图层.resize(缩放比例, 缩放比例, AnchorPosition.MIDDLECENTER);
} else {
alert("未找到名为'字体'的图层");
}
}
function 多选背景() //自由变换
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putName(stringIDToTypeID("layer"), "背景");
d.putReference(stringIDToTypeID("null"), r);
d.putEnumerated(stringIDToTypeID("selectionModifier"), stringIDToTypeID("selectionModifierType"), stringIDToTypeID("addToSelection"));
d.putBoolean(stringIDToTypeID("makeVisible"), false);
var list = new ActionList();
list.putInteger(1);
list.putInteger(13);
d.putList(stringIDToTypeID("layerID"), list);
executeAction(stringIDToTypeID("select"), d, DialogModes.NO);
}
function 底对齐() //底对齐
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
d.putEnumerated(stringIDToTypeID("using"), stringIDToTypeID("alignDistributeSelector"), stringIDToTypeID("ADSBottoms"));
d.putBoolean(stringIDToTypeID("alignToCanvas"), false);
executeAction(stringIDToTypeID("align"), d, DialogModes.NO);
}
function 水平居中对齐() //水平居中对齐
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
d.putEnumerated(stringIDToTypeID("using"), stringIDToTypeID("alignDistributeSelector"), stringIDToTypeID("ADSCentersH"));
d.putBoolean(stringIDToTypeID("alignToCanvas"), false);
executeAction(stringIDToTypeID("align"), d, DialogModes.NO);
}
// 设置单位为像素
dialog.show();
}
"""

View File

@@ -0,0 +1,370 @@
dxf24_jscode = """
// 设置单位为像素
function 自动米样拼贴(){
var dialog = new Window("dialog");
dialog.text = "SO自动米样拼贴";
dialog.orientation = "row";
dialog.alignChildren = ["left","top"];
dialog.spacing = 10;
dialog.margins = 16;
// GROUP1
// ======
var group1 = dialog.add("group", undefined, {name: "group1"});
group1.orientation = "column";
group1.alignChildren = ["fill","top"];
group1.spacing = 10;
group1.margins = 0;
// PANEL1
// ======
var panel1 = group1.add("panel", undefined, undefined, {name: "panel1"});
panel1.text = "源图像";
panel1.preferredSize.width = 388;
panel1.preferredSize.height = 205;
panel1.orientation = "column";
panel1.alignChildren = ["left","top"];
panel1.spacing = 10;
panel1.margins = 10;
var statictext1 = panel1.add("statictext", undefined, undefined, {name: "statictext1"});
statictext1.text = "使用:";
// GROUP2
// ======
var group2 = panel1.add("group", undefined, {name: "group2"});
group2.orientation = "row";
group2.alignChildren = ["left","center"];
group2.spacing = 10;
group2.margins = 0;
var button1 = group2.add("button", undefined, undefined, {name: "button1"});
button1.text = "选取";
var edittext1 = group2.add('edittext {properties: {name: "edittext1"}}');
edittext1.text = "[选择图像文件夹]";
edittext1.preferredSize.width = 300;
// PANEL2
// ======
var panel2 = group1.add("panel", undefined, undefined, {name: "panel2"});
panel2.text = "SO小样文档";
panel2.preferredSize.height = 160;
panel2.orientation = "column";
panel2.alignChildren = ["left","top"];
panel2.spacing = 10;
panel2.margins = 10;
var statictext2 = panel2.add("statictext", undefined, undefined, {name: "statictext2"});
statictext2.text = "设定:";
// GROUP3
// ======
var group3 = panel2.add("group", undefined, {name: "group3"});
group3.orientation = "row";
group3.alignChildren = ["left","center"];
group3.spacing = 10;
group3.margins = 0;
var statictext3 = group3.add("statictext", undefined, undefined, {name: "statictext3"});
statictext3.text = "幅宽(cm):";
var edittext2 = group3.add('edittext {properties: {name: "edittext2"}}');
edittext2.preferredSize.width = 100;
// GROUP4
// ======
var group4 = panel2.add("group", undefined, {name: "group4"});
group4.orientation = "row";
group4.alignChildren = ["left","center"];
group4.spacing = 10;
group4.margins = 0;
// GROUP5
// ======
var group5 = group1.add("group", undefined, {name: "group5"});
group5.orientation = "row";
group5.alignChildren = ["left","center"];
group5.spacing = 10;
group5.margins = 0;
// PANEL3
// ======
// GROUP7
// ======
var group7 = dialog.add("group", undefined, {name: "group7"});
group7.orientation = "column";
group7.alignChildren = ["fill","top"];
group7.spacing = 10;
group7.margins = 0;
var ok = group7.add("button", undefined, undefined, {name: "ok"});
ok.text = "确认";
var cancel = group7.add("button", undefined, undefined, {name: "cancel"});
cancel.text = "取消";
var dialog = new Window("dialog");
dialog.text = "SO自动米样拼贴";
dialog.orientation = "row";
dialog.alignChildren = ["left","top"];
dialog.spacing = 10;
dialog.margins = 16;
// GROUP1
// ======
var group1 = dialog.add("group", undefined, {name: "group1"});
group1.orientation = "column";
group1.alignChildren = ["fill","top"];
group1.spacing = 10;
group1.margins = 0;
// PANEL1
// ======
var panel1 = group1.add("panel", undefined, undefined, {name: "panel1"});
panel1.text = "源图像";
panel1.preferredSize.width = 388;
panel1.preferredSize.height = 205;
panel1.orientation = "column";
panel1.alignChildren = ["left","top"];
panel1.spacing = 10;
panel1.margins = 10;
var statictext1 = panel1.add("statictext", undefined, undefined, {name: "statictext1"});
statictext1.text = "使用:";
// GROUP2
// ======
var group2 = panel1.add("group", undefined, {name: "group2"});
group2.orientation = "row";
group2.alignChildren = ["left","center"];
group2.spacing = 10;
group2.margins = 0;
var button1 = group2.add("button", undefined, undefined, {name: "button1"});
button1.text = "选取";
var edittext1 = group2.add('edittext {properties: {name: "edittext1"}}');
edittext1.text = "[选择图像文件夹]";
edittext1.preferredSize.width = 300;
// PANEL2
// ======
var panel2 = group1.add("panel", undefined, undefined, {name: "panel2"});
panel2.text = "SO小样文档拼贴";
panel2.preferredSize.height = 160;
panel2.orientation = "column";
panel2.alignChildren = ["left","top"];
panel2.spacing = 10;
panel2.margins = 10;
var statictext2 = panel2.add("statictext", undefined, undefined, {name: "statictext2"});
statictext2.text = "设定:";
// GROUP3
// ======
var group3 = panel2.add("group", undefined, {name: "group3"});
group3.orientation = "row";
group3.alignChildren = ["left","center"];
group3.spacing = 10;
group3.margins = 0;
var statictext3 = group3.add("statictext", undefined, undefined, {name: "statictext3"});
statictext3.text = "幅宽(cm):";
var edittext2 = group3.add('edittext {properties: {name: "edittext2"}}');
edittext2.preferredSize.width = 100;
// GROUP4
// ======
var group4 = panel2.add("group", undefined, {name: "group4"});
group4.orientation = "row";
group4.alignChildren = ["left","center"];
group4.spacing = 10;
group4.margins = 0;
// GROUP5
// ======
var group5 = group1.add("group", undefined, {name: "group5"});
group5.orientation = "row";
group5.alignChildren = ["left","center"];
group5.spacing = 10;
group5.margins = 0;
// PANEL3
// ======
// GROUP7
// ======
var group7 = dialog.add("group", undefined, {name: "group7"});
group7.orientation = "column";
group7.alignChildren = ["fill","top"];
group7.spacing = 10;
group7.margins = 0;
var ok = group7.add("button", undefined, undefined, {name: "ok"});
ok.text = "确认";
var cancel = group7.add("button", undefined, undefined, {name: "cancel"});
cancel.text = "取消";
button1.onClick = function () {
// 打开文件夹选择对话框
var selectedFolder = Folder.selectDialog("选择图像文件夹");
// 检查用户是否取消了选择
if (selectedFolder) {
// 将选择的文件夹路径显示在输入框中
edittext1.text = selectedFolder.fsName;
}
};
ok.onClick = function () {
app.preferences.rulerUnits = Units.PIXELS;
//function 创建拼贴图(导入文件夹路径, 文档宽度厘米) {
// 假设这些值是从某处获取或者用户输入的
var 导入文件夹路径 =new Folder (edittext1.text);
var 文档宽度厘米 = Number(edittext2.text);
var 文档高度厘米 = 300; // 例如50厘米
var 分辨率 = 200; // 分辨率设置为150 DPI
// 转换厘米到像素
var 厘米到像素的转换系数 = 2.54;
var 文档宽度像素 = 文档宽度厘米 / 厘米到像素的转换系数 * 分辨率;
var 文档高度像素 = 文档高度厘米 / 厘米到像素的转换系数 * 分辨率;
var 导入文件夹 = new Folder(导入文件夹路径);
var 文件列表 = 导入文件夹.getFiles("*.*");
var 文件名数组 = new Array();
var 文件宽度数组 = new Array();
var 文件高度数组 = new Array();
// 读取文件列表并获取文件信息
for (var 索引1 = 0; 索引1 < 文件列表.length; 索引1++) {
var 文档 = app.open(文件列表[索引1]);
文件名数组[索引1] = 文档.fullName;
文件宽度数组[索引1] = parseInt(文档.width);
文件高度数组[索引1] = parseInt(文档.height);
文档.close();
}
// 根据高度对文件进行排序
for (var 索引1 = 文件高度数组.length - 1; 索引1 > 0; --索引1) {
for (var 索引2 = 0; 索引2 < 索引1; ++索引2) {
if (文件高度数组[索引2] > 文件高度数组[索引2 + 1])
交换数组元素(索引2, 索引2 + 1);
}
}
function 交换数组元素(索引1, 索引2) {
var 临时 = 文件高度数组[索引1];
文件高度数组[索引1] = 文件高度数组[索引2];
文件高度数组[索引2] = 临时;
var 临时2 = 文件宽度数组[索引1];
文件宽度数组[索引1] = 文件宽度数组[索引2];
文件宽度数组[索引2] = 临时2;
var 临时3 = 文件名数组[索引1];
文件名数组[索引1] = 文件名数组[索引2];
文件名数组[索引2] = 临时3;
}
// 创建新文档并添加图片
var 新文档 = app.documents.add(文档宽度像素, 文档高度像素, 分辨率, "拼贴", NewDocumentMode.CMYK, DocumentFill.WHITE);
var 当前顶部 = 0;
var 当前左侧 = 0;
for (var 索引1 = 0; 索引1 < 文件名数组.length; 索引1++) {
var 文档 = app.open(文件名数组[索引1]);
文档.selection.selectAll();
文档.selection.copy();
文档.close();
if ((当前左侧 + 文件宽度数组[索引1]) > 文档宽度像素) {
当前左侧 = 0;
当前顶部 += 文件高度数组[索引1 - 1];
}
var 边界 = [
[当前左侧, 当前顶部],
[当前左侧 + 文件宽度数组[索引1], 当前顶部],
[当前左侧 + 文件宽度数组[索引1], 当前顶部 + 文件高度数组[索引1]],
[当前左侧, 当前顶部 + 文件高度数组[索引1]]
];
新文档.selection.select(边界, SelectionType.REPLACE, 0, true);
新文档.paste();
当前左侧 += 文件宽度数组[索引1];
}
// 选择输出文件夹并保存图片
var 输出文件夹 = new Folder(edittext1.text + "/拼贴");
if (!输出文件夹.exists) 输出文件夹.create();
// 设置TIFF保存选项
var tiffSaveOptions = new TiffSaveOptions();
tiffSaveOptions.imageCompression = TIFFEncoding.TIFFLZW; // 使用LZW压缩
tiffSaveOptions.byteOrder = ByteOrder.IBM; // 设置字节顺序为IBM大端序
// 定义保存的文件路径和名称
var 文件 = new File(输出文件夹 + "/combined.tif");
// 保存当前文档为TIFF格式
新文档.saveAs(文件, tiffSaveOptions, true, Extension.LOWERCASE);
裁切透明像素();
// 关闭文档,不保存更改
//新文档.close(SaveOptions.DONOTSAVECHANGES);
dialog.close();
alert("拼贴完成")
}
function 裁切透明像素() {
var 文档 = app.activeDocument; // 获取当前活动的文档
// 裁切透明像素
// TrimType.TOPLEFT 表示从图像的左上角开始裁切
// 第二个参数 true 表示裁切顶部的透明像素
// 第三个参数 true 表示裁切左侧的透明像素
// 第四个参数 true 表示裁切底部的透明像素
// 第五个参数 true 表示裁切右侧的透明像素
文档.trim(TrimType.TOPLEFT, true, true, true, true);
}
dialog.show();
}
"""

View File

@@ -0,0 +1,6 @@
dxf25_jscode = """
alert("接口测试")
"""

View File

@@ -0,0 +1,218 @@
dxf26_jscode = """
// 弹出文件夹选择框
function 模特换图(){
建立快照()
var folder = Folder.selectDialog("请选择一个文件夹");
var 模特文档 = app.activeDocument;
if (folder) {
// 在选择的文件夹中创建一个新的子文件夹
var targetFolder = new Folder(folder.fullName + "/模特图生成");
if (!targetFolder.exists) {
targetFolder.create();
}
var files = folder.getFiles();
// 获取“贴图位置”图层组中的所有图层名称
var layerSet = 模特文档.layerSets.getByName("贴图位置");
var layerNames = [];
for (var j = 0; j < layerSet.artLayers.length; j++) {
layerNames.push(layerSet.artLayers[j].name);
}
// 遍历并尝试打开每个文件
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (file instanceof File) {
try {
app.open(file);
app.activeDocument.flatten()
var 当前文档 = app.activeDocument;
var 当前文档名称 = 当前文档.name;
图像大小();
预设图案(当前文档名称);
app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
app.activeDocument = 模特文档;
var 水平增量 = 200;
var 垂直增量 = 300;
var 水平基数 = 200;
var 垂直基数 = 300;
// 遍历“贴图位置”图层组中的每个图层
for (var k = 0; k < layerNames.length; k++) {
var layname = layerNames[k];
var 贴图位置 = app.activeDocument.layerSets.getByName("贴图位置").layers.getByName(layname);
app.activeDocument.activeLayer = 贴图位置;
载入选区();
填充图案(当前文档名称);
栅格化图层()
取消链接蒙版()
var 水平 = 水平基数 + 水平增量 * k;
var 垂直 = 垂直基数 + 垂直增量 * k;
位移(水平, 垂直);
}
var saveFile = new File(targetFolder.fullName + "/" + file.name.replace(/\.[^\.]+$/, "") + ".tif");
var tiffSaveOptions = new TiffSaveOptions();
tiffSaveOptions.imageCompression = TIFFEncoding.NONE; // 或者根据需要设置其他压缩选项
tiffSaveOptions.alphaChannels = true;
tiffSaveOptions.layers = true;
app.activeDocument.saveAs(saveFile, tiffSaveOptions, true, Extension.LOWERCASE);
// 关闭当前文档
历史记录回退到快照1()
} catch (e) {
alert("无法打开文件: " );
}
}
}
alert("换图完成")
} else {
alert("没有选择文件夹");
}
// 其他函数保持不变
function generateRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function 图像大小() //图像大小
{
var d = new ActionDescriptor();
d.putUnitDouble(stringIDToTypeID("resolution"), stringIDToTypeID("densityUnit"), 150);
d.putBoolean(stringIDToTypeID("scaleStyles"), true);
d.putBoolean(stringIDToTypeID("constrainProportions"), true);
d.putEnumerated(charIDToTypeID("Intr"), stringIDToTypeID("interpolationType"), stringIDToTypeID("nearestNeighbor"));
executeAction(stringIDToTypeID("imageSize"), d, DialogModes.NO);
}
function 取消链接蒙版() //取消链接蒙版
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
var d1 = new ActionDescriptor();
d1.putBoolean(stringIDToTypeID("userMaskLinked"), false);
d.putObject(stringIDToTypeID("to"), stringIDToTypeID("layer"), d1);
executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
}
function 栅格化图层() //栅格化图层
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
executeAction(stringIDToTypeID("rasterizeLayer"), d, DialogModes.NO);
}
function 预设图案(当前文档名称) //
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putClass(stringIDToTypeID("pattern"));
d.putReference(stringIDToTypeID("null"), r);
var r1 = new ActionReference();
r1.putProperty(stringIDToTypeID("property"), stringIDToTypeID("selection"));
r1.putEnumerated(stringIDToTypeID("document"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("using"), r1);
d.putString(stringIDToTypeID("name"), 当前文档名称);
executeAction(stringIDToTypeID("make"), d, DialogModes.NO);
}
function 载入选区() //载入选区
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("channel"), stringIDToTypeID("selection"));
d.putReference(stringIDToTypeID("null"), r);
var r1 = new ActionReference();
r1.putEnumerated(stringIDToTypeID("channel"), stringIDToTypeID("channel"), stringIDToTypeID("transparencyEnum"));
d.putReference(stringIDToTypeID("to"), r1);
executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
}
function 填充图案(当前文档名称) //
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putClass(stringIDToTypeID("contentLayer"));
d.putReference(stringIDToTypeID("null"), r);
var d1 = new ActionDescriptor();
var d2 = new ActionDescriptor();
var d3 = new ActionDescriptor();
d3.putString(stringIDToTypeID("name"), 当前文档名称);
d2.putObject(stringIDToTypeID("pattern"), stringIDToTypeID("pattern"), d3);
d1.putObject(stringIDToTypeID("type"), stringIDToTypeID("patternLayer"), d2);
d.putObject(stringIDToTypeID("using"), stringIDToTypeID("contentLayer"), d1);
executeAction(stringIDToTypeID("make"), d, DialogModes.NO);
}
function 位移(水平,垂直) //位移
{
var d = new ActionDescriptor();
d.putInteger(stringIDToTypeID("horizontal"), 水平);
d.putInteger(stringIDToTypeID("vertical"), 垂直);
d.putEnumerated(stringIDToTypeID("fill"), stringIDToTypeID("fillMode"), stringIDToTypeID("wrap"));
executeAction(stringIDToTypeID("offset"), d, DialogModes.NO);
}
function 历史记录回退到快照1() //
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putName(stringIDToTypeID("snapshotClass"), "快照 1");
d.putReference(stringIDToTypeID("null"), r);
executeAction(stringIDToTypeID("select"), d, DialogModes.NO);
}
function 建立快照() //打开
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putClass(stringIDToTypeID("snapshotClass"));
d.putReference(stringIDToTypeID("null"), r);
var r1 = new ActionReference();
r1.putProperty(stringIDToTypeID("historyState"), stringIDToTypeID("currentHistoryState"));
d.putReference(stringIDToTypeID("from"), r1);
executeAction(stringIDToTypeID("make"), d, DialogModes.NO);
}
}
"""

View File

@@ -0,0 +1,500 @@
dxf27_jscode = """
function 新的米样缩放()
{
var dialog = new Window("dialog");
dialog.text = "S/O样自动缩放";
//dialog.text = "SO自动米样拼贴";
dialog.orientation = "row";
dialog.alignChildren = ["left","top"];
dialog.spacing = 10;
dialog.margins = 16;
// GROUP1
// ======
var group1 = dialog.add("group", undefined, {name: "group1"});
group1.orientation = "column";
group1.alignChildren = ["fill","top"];
group1.spacing = 10;
group1.margins = 0;
// PANEL1
// ======
var panel1 = group1.add("panel", undefined, undefined, {name: "panel1"});
panel1.text = "源图像";
panel1.preferredSize.width = 388;
panel1.preferredSize.height = 205;
panel1.orientation = "column";
panel1.alignChildren = ["left","top"];
panel1.spacing = 10;
panel1.margins = 10;
var statictext1 = panel1.add("statictext", undefined, undefined, {name: "statictext1"});
statictext1.text = "使用:";
// GROUP2
// ======
var group2 = panel1.add("group", undefined, {name: "group2"});
group2.orientation = "row";
group2.alignChildren = ["left","center"];
group2.spacing = 10;
group2.margins = 0;
var button1 = group2.add("button", undefined, undefined, {name: "button1"});
button1.text = "选取";
var edittext1 = group2.add('edittext {properties: {name: "edittext1"}}');
edittext1.text = "[选择图像文件夹]";
edittext1.preferredSize.width = 300;
// PANEL2
// ======
var panel2 = group1.add("panel", undefined, undefined, {name: "panel2"});
panel2.text = "SO小样文档";
panel2.preferredSize.height = 160;
panel2.orientation = "column";
panel2.alignChildren = ["left","top"];
panel2.spacing = 10;
panel2.margins = 10;
var statictext2 = panel2.add("statictext", undefined, undefined, {name: "statictext2"});
statictext2.text = "设定:";
// GROUP3
// ======
var group3 = panel2.add("group", undefined, {name: "group3"});
group3.orientation = "row";
group3.alignChildren = ["left","center"];
group3.spacing = 10;
group3.margins = 0;
var statictext3 = group3.add("statictext", undefined, undefined, {name: "statictext3"});
statictext3.text = "宽度(cm):";
var edittext2 = group3.add('edittext {properties: {name: "edittext2"}}');
edittext2.preferredSize.width = 100;
var statictext4 = group3.add("statictext", undefined, undefined, {name: "statictext4"});
statictext4.text = "高度(cm):";
var edittext3 = group3.add('edittext {properties: {name: "edittext3"}}');
edittext3.preferredSize.width = 100;
// GROUP4
// ======
var group4 = panel2.add("group", undefined, {name: "group4"});
group4.orientation = "row";
group4.alignChildren = ["left","center"];
group4.spacing = 10;
group4.margins = 0;
// GROUP5
// ======
var group5 = group1.add("group", undefined, {name: "group5"});
group5.orientation = "row";
group5.alignChildren = ["left","center"];
group5.spacing = 10;
group5.margins = 0;
// PANEL3
// ======
// GROUP7
// ======
var group7 = dialog.add("group", undefined, {name: "group7"});
group7.orientation = "column";
group7.alignChildren = ["fill","top"];
group7.spacing = 10;
group7.margins = 0;
var ok = group7.add("button", undefined, undefined, {name: "ok"});
ok.text = "确认";
var cancel = group7.add("button", undefined, undefined, {name: "cancel"});
cancel.text = "取消";
button1.onClick = function () {
// 打开文件夹选择对话框
var selectedFolder = Folder.selectDialog("选择图像文件夹");
// 检查用户是否取消了选择
if (selectedFolder) {
// 将选择的文件夹路径显示在输入框中
edittext1.text = selectedFolder.fsName;
}
};
ok.onClick = function () {
app.preferences.rulerUnits = Units.PIXELS;
var 素材图片文件夹 = new Folder(edittext1.text);
var 遍历tiff = 素材图片文件夹.getFiles("*.*");
// 新建文件夹
var 新文件夹 = new Folder(edittext1.text + "/SO小样拼贴");
新文件夹.create();
var 新加字文件夹 = new Folder(edittext1.text + "/SO小样拼贴加字");
新加字文件夹.create();
宽度=Number (edittext2.text);
高度=Number (edittext3.text);
for (var i = 0; i < 遍历tiff.length; i++) {
if (遍历tiff[i] instanceof File) {
app.open(遍历tiff[i]);
app.activeDocument.flatten();
var 当前文档 = app.activeDocument;
var 当前文档名称 = 当前文档.name;
resizeImageToCm(宽度, 高度,200);
/*
图像大小()
预设图案(当前文档名称);
app.activeDocument.crop([UnitValue("0px"), UnitValue("0px"), UnitValue(宽度, "cm"), UnitValue(高度, "cm")]);
填充图案(当前文档名称);
app.activeDocument.flatten();
画布扩展()
*/
画布扩展()
// 保存新的图像文件到新建的文件夹中
var 保存路径 = 新文件夹 + "/" + 当前文档名称;
var tifSaveOpt = new TiffSaveOptions();
tifSaveOpt.imageCompression = TIFFEncoding.TIFFLZW;
tifSaveOpt.byteOrder = ByteOrder.IBM;
var asCopy = true;
app.activeDocument.saveAs(new File(保存路径), tifSaveOpt, asCopy);
创建并处理文本图层();
app.activeDocument.flatten();
var 保存路径 = 新加字文件夹 + "/" + 当前文档名称;
var tifSaveOpt = new TiffSaveOptions();
tifSaveOpt.imageCompression = TIFFEncoding.TIFFLZW;
tifSaveOpt.byteOrder = ByteOrder.IBM;
var asCopy = true;
app.activeDocument.saveAs(new File(保存路径), tifSaveOpt, asCopy);
app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
}
}
//alert("小样连晒完成")
dialog.close();
// 创建并保存拼贴图像(新文件夹, 幅宽)
};
function resizeImageToCm(widthCm, heightCm, resolution) {
// 将厘米转换为像素
var widthInPixels = widthCm * (resolution / 2.54);
var heightInPixels = heightCm * (resolution / 2.54);
// 调整图像大小
app.activeDocument.resizeImage(widthInPixels, heightInPixels, resolution, ResampleMethod.NEARESTNEIGHBOR);
}
// 使用示例:将图像大小调整为 10cm x 15cm分辨率为 300 像素/英寸
function 预设图案(当前文档名称) //
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putClass(stringIDToTypeID("pattern"));
d.putReference(stringIDToTypeID("null"), r);
var r1 = new ActionReference();
r1.putProperty(stringIDToTypeID("property"), stringIDToTypeID("selection"));
r1.putEnumerated(stringIDToTypeID("document"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("using"), r1);
d.putString(stringIDToTypeID("name"), 当前文档名称);
executeAction(stringIDToTypeID("make"), d, DialogModes.NO);
}
function 填充图案(当前文档名称) //
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putClass(stringIDToTypeID("contentLayer"));
d.putReference(stringIDToTypeID("null"), r);
var d1 = new ActionDescriptor();
var d2 = new ActionDescriptor();
var d3 = new ActionDescriptor();
d3.putString(stringIDToTypeID("name"), 当前文档名称);
d2.putObject(stringIDToTypeID("pattern"), stringIDToTypeID("pattern"), d3);
d1.putObject(stringIDToTypeID("type"), stringIDToTypeID("patternLayer"), d2);
d.putObject(stringIDToTypeID("using"), stringIDToTypeID("contentLayer"), d1);
executeAction(stringIDToTypeID("make"), d, DialogModes.NO);
}
function 图像大小() //图像大小
{
var d = new ActionDescriptor();
d.putUnitDouble(stringIDToTypeID("resolution"), stringIDToTypeID("densityUnit"), 200);
d.putBoolean(stringIDToTypeID("scaleStyles"), true);
d.putBoolean(stringIDToTypeID("constrainProportions"), true);
d.putEnumerated(charIDToTypeID("Intr"), stringIDToTypeID("interpolationType"), stringIDToTypeID("nearestNeighbor"));
executeAction(stringIDToTypeID("imageSize"), d, DialogModes.NO);
}
function 画布扩展() //
{
var d = new ActionDescriptor();
d.putBoolean(stringIDToTypeID("relative"), true);
d.putUnitDouble(stringIDToTypeID("width"), stringIDToTypeID("distanceUnit"), 14.4);
d.putUnitDouble(stringIDToTypeID("height"), stringIDToTypeID("distanceUnit"), 14.4);
d.putEnumerated(stringIDToTypeID("horizontal"), stringIDToTypeID("horizontalLocation"), stringIDToTypeID("center"));
d.putEnumerated(stringIDToTypeID("vertical"), stringIDToTypeID("verticalLocation"), stringIDToTypeID("center"));
d.putEnumerated(stringIDToTypeID("canvasExtensionColorType"), stringIDToTypeID("canvasExtensionColorType"), stringIDToTypeID("color"));
var d1 = new ActionDescriptor();
d1.putDouble(stringIDToTypeID("red"), 255);
d1.putDouble(stringIDToTypeID("green"), 255);
d1.putDouble(stringIDToTypeID("blue"), 255);
d.putObject(stringIDToTypeID("canvasExtensionColor"), stringIDToTypeID("RGBColor"), d1);
executeAction(stringIDToTypeID("canvasSize"), d, DialogModes.NO);
}
function 创建并处理文本图层() {
// 新建图层
var textLayer = activeDocument.artLayers.add();
// 将新建图层变成文本图层
textLayer.kind = LayerKind.TEXT;
// 将文本内容改为当前文档name
textLayer.textItem.contents = activeDocument.name;
// 字体大小固定值
var 固定字体大小 = 30; // 例如30像素
textLayer.textItem.size = 固定字体大小;
// 文字字体固定值
textLayer.textItem.font = "微软雅黑";
// 计算并调整文本位置
var x = activeDocument.width - textLayer.bounds[2];
var y = textLayer.bounds[1];
textLayer.translate(x, -y);
// 偏移
textLayer.translate(UnitValue("-1cm"), UnitValue("+0.5cm"));
// 复制并栅格化图层
var copyLayer = textLayer.duplicate();
copyLayer.rasterize(RasterizeType.ENTIRELAYER);
// 设置固定颜色值
var 固定颜色 = new SolidColor();
固定颜色.rgb.red = 255; // 红色分量
固定颜色.rgb.green = 255; // 绿色分量
固定颜色.rgb.blue = 255; // 蓝色分量
activeDocument.activeLayer = copyLayer;
activeDocument.selection.fill(固定颜色, ColorBlendMode.NORMAL, 100, true);
// 白边
activeDocument.activeLayer.applyMinimum(10);
后移一层()
向上选择()
向下合并()
名称更改字体()
缩小字体图层至文档一半()
多选背景()
底对齐()
水平居中对齐()
}
// 调用函数
function 后移一层() //
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
var r1 = new ActionReference();
r1.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("previous"));
d.putReference(stringIDToTypeID("to"), r1);
executeAction(stringIDToTypeID("move"), d, DialogModes.NO);
}
function 向上选择() //
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("forwardEnum"));
d.putReference(stringIDToTypeID("null"), r);
d.putBoolean(stringIDToTypeID("makeVisible"), false);
var list = new ActionList();
list.putInteger(19);
d.putList(stringIDToTypeID("layerID"), list);
executeAction(stringIDToTypeID("select"), d, DialogModes.NO);
}
function 向下合并() //向下合并
{
var d = new ActionDescriptor();
executeAction(stringIDToTypeID("mergeLayersNew"), d, DialogModes.NO);
}
function 名称更改字体() //名称更改
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
var d1 = new ActionDescriptor();
d1.putString(stringIDToTypeID("name"), "字体");
d.putObject(stringIDToTypeID("to"), stringIDToTypeID("layer"), d1);
executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
}
function 缩小字体图层至文档一半() {
var 文档 = app.activeDocument;
var 字体图层 = null;
// 遍历文档中的图层以找到名为"字体"的图层
for (var i = 0; i < 文档.artLayers.length; i++) {
if (文档.artLayers[i].name === "字体") {
字体图层 = 文档.artLayers[i];
break;
}
}
if (字体图层 !== null) {
// 获取文档的宽度的一半
var 目标宽度 = 文档.width / 2;
// 获取图层的当前宽度
var 图层宽度 = 字体图层.bounds[2] - 字体图层.bounds[0];
// 计算缩放比例
var 缩放比例 = 目标宽度 / 图层宽度 * 100;
// 缩放图层
字体图层.resize(缩放比例, 缩放比例, AnchorPosition.MIDDLECENTER);
} else {
alert("未找到名为'字体'的图层");
}
}
function 多选背景() //自由变换
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putName(stringIDToTypeID("layer"), "背景");
d.putReference(stringIDToTypeID("null"), r);
d.putEnumerated(stringIDToTypeID("selectionModifier"), stringIDToTypeID("selectionModifierType"), stringIDToTypeID("addToSelection"));
d.putBoolean(stringIDToTypeID("makeVisible"), false);
var list = new ActionList();
list.putInteger(1);
list.putInteger(13);
d.putList(stringIDToTypeID("layerID"), list);
executeAction(stringIDToTypeID("select"), d, DialogModes.NO);
}
function 底对齐() //底对齐
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
d.putEnumerated(stringIDToTypeID("using"), stringIDToTypeID("alignDistributeSelector"), stringIDToTypeID("ADSBottoms"));
d.putBoolean(stringIDToTypeID("alignToCanvas"), false);
executeAction(stringIDToTypeID("align"), d, DialogModes.NO);
}
function 水平居中对齐() //水平居中对齐
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
d.putEnumerated(stringIDToTypeID("using"), stringIDToTypeID("alignDistributeSelector"), stringIDToTypeID("ADSCentersH"));
d.putBoolean(stringIDToTypeID("alignToCanvas"), false);
executeAction(stringIDToTypeID("align"), d, DialogModes.NO);
}
// 设置单位为像素
dialog.show();
}
"""

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,778 @@
dxf6_jscode = """
function 前景色修改() //取消选择
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("color"), stringIDToTypeID("foregroundColor"));
d.putReference(stringIDToTypeID("null"), r);
var d1 = new ActionDescriptor();
d1.putDouble(stringIDToTypeID("cyan"), 20);
d1.putDouble(stringIDToTypeID("magenta"), 0);
d1.putDouble(stringIDToTypeID("yellowColor"), 0);
d1.putDouble(stringIDToTypeID("black"), 0);
d.putObject(stringIDToTypeID("to"), stringIDToTypeID("CMYKColorClass"), d1);
d.putString(stringIDToTypeID("source"), "photoshopPicker");
executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
}
function 图像切割2() {
app.activeDocument.suspendHistory("图像切割", "图像切割()");
}
function 图像切割() {
画布大小()
app.preferences.rulerUnits = Units.PIXELS
var currentDocument = app.activeDocument;
var matchCount = 0; // 匹配到的数值计数
var existingPatternSet = false;
var layerNames = []; // 保存匹配到的图层名称的数组
// 遍历图层
for (var j = 0; j < currentDocument.layers.length; j++) {
var layer = currentDocument.layers[j];
var layerName = layer.name;
// 检查图层名称是否以P开头并且后面跟着数字
if (/^P\d+$/.test(layerName)) {
matchCount++;
layerNames.push(layer); // 将匹配到的图层添加到数组中
}
}
// 输出匹配到的数值个数
// $.writeln("匹配到的数值个数:" + matchCount);
// 遍历匹配到的图层名称
for (var i = 0; i < layerNames.length; i++) {
var layerName = layerNames[i].name;
$.writeln("匹配到的图层名称:" + layerName);
var 当前花样图层 = app.activeDocument.layers.getByName(layerName);
app.activeDocument.activeLayer = 当前花样图层;
切换mask()
载入选区()
var 边距 = 获取当前选区四边距();
var 毫米 = 130;
var 每英寸像素数 = app.activeDocument.resolution; // 获取当前文档的分辨率(每英寸像素数)
var 扩展像素 = 毫米转像素(毫米, 每英寸像素数);
var 裁切上边距= 边距.top-扩展像素
var 裁切左边距= 边距.left-扩展像素
var 裁切下边距= 边距.bottom+扩展像素
var 裁切右边距= 边距.right+扩展像素
var selRegion = [
[裁切左边距,裁切上边距],
[裁切右边距,裁切上边距],
[裁切右边距,裁切下边距],
[裁切左边距,裁切下边距]
];
app.activeDocument.selection.select(selRegion, SelectionType.REPLACE);
新建图层()
app.activeDocument.selection.select(selRegion, SelectionType.REPLACE);
var c = new SolidColor();
c.rgb.hexValue = "FFFFFF";
app.activeDocument.selection.fill(c);
后移一层()
app.activeDocument.activeLayer = 当前花样图层;
切换mask()
载入选区()
删除图层蒙版()
创建剪贴蒙版()
向下合并()
添加图层蒙版()
当前图层=app.activeDocument.activeLayer
当前图层.name=layerName
}
}
function 切换mask() //取消选择
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("channel"), stringIDToTypeID("channel"), stringIDToTypeID("mask"));
d.putReference(stringIDToTypeID("null"), r);
d.putBoolean(stringIDToTypeID("makeVisible"), false);
executeAction(stringIDToTypeID("select"), d, DialogModes.NO);
}
function 毫米转像素(毫米, 每英寸像素数) {
var 每英寸毫米数 = 25.4;
var 英寸 = 毫米 / 每英寸毫米数;
return Math.round(英寸 * 每英寸像素数);
}
function 画布大小() //画布大小
{
var d = new ActionDescriptor();
d.putBoolean(stringIDToTypeID("relative"), true);
d.putUnitDouble(stringIDToTypeID("width"), stringIDToTypeID("distanceUnit"), 850.56);
d.putUnitDouble(stringIDToTypeID("height"), stringIDToTypeID("distanceUnit"), 850.56);
d.putEnumerated(stringIDToTypeID("horizontal"), stringIDToTypeID("horizontalLocation"), stringIDToTypeID("center"));
d.putEnumerated(stringIDToTypeID("vertical"), stringIDToTypeID("verticalLocation"), stringIDToTypeID("center"));
executeAction(stringIDToTypeID("canvasSize"), d, DialogModes.NO);
}
function 载入选区() //载入选区
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("channel"), stringIDToTypeID("selection"));
d.putReference(stringIDToTypeID("null"), r);
var r1 = new ActionReference();
r1.putEnumerated(stringIDToTypeID("channel"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("to"), r1);
executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
}
function 获取当前选区四边距() {
var currentDocument = app.activeDocument;
var selectionBounds = currentDocument.selection.bounds;
var top = selectionBounds[1].value;
var left = selectionBounds[0].value;
var bottom = selectionBounds[3].value;
var right = selectionBounds[2].value;
return {
top: top,
left: left,
bottom: bottom,
right: right
};
}
function 新建图层() //新建图层
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putClass(stringIDToTypeID("layer"));
d.putReference(stringIDToTypeID("null"), r);
d.putInteger(stringIDToTypeID("layerID"), 135);
executeAction(stringIDToTypeID("make"), d, DialogModes.NO);
}
function 后移一层() //后移一层
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
var r1 = new ActionReference();
r1.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("previous"));
d.putReference(stringIDToTypeID("to"), r1);
executeAction(stringIDToTypeID("move"), d, DialogModes.NO);
}
function 删除图层蒙版() //删除图层蒙版
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("channel"), stringIDToTypeID("channel"), stringIDToTypeID("mask"));
d.putReference(stringIDToTypeID("null"), r);
executeAction(stringIDToTypeID("delete"), d, DialogModes.NO);
}
function 载入选区() //载入选区
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("channel"), stringIDToTypeID("selection"));
d.putReference(stringIDToTypeID("null"), r);
var r1 = new ActionReference();
r1.putEnumerated(stringIDToTypeID("channel"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("to"), r1);
executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
}
function 删除图层蒙版() //删除图层蒙版
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("channel"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
executeAction(stringIDToTypeID("delete"), d, DialogModes.NO);
}
function 向下合并() //向下合并
{
var d = new ActionDescriptor();
executeAction(stringIDToTypeID("mergeLayersNew"), d, DialogModes.NO);
}
function 添加图层蒙版() //添加图层蒙版
{
var d = new ActionDescriptor();
d.putClass(stringIDToTypeID("new"), stringIDToTypeID("channel"));
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("channel"), stringIDToTypeID("channel"), stringIDToTypeID("mask"));
d.putReference(stringIDToTypeID("at"), r);
d.putEnumerated(stringIDToTypeID("using"), stringIDToTypeID("userMaskEnabled"), stringIDToTypeID("revealSelection"));
executeAction(stringIDToTypeID("make"), d, DialogModes.NO);
}
function 创建剪贴蒙版() //创建剪贴蒙版
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
executeAction(stringIDToTypeID("groupEvent"), d, DialogModes.NO);
}
function 右下对齐2() {
app.activeDocument.suspendHistory("右下对齐", "右下对齐()");
}
function 右下对齐() {
var groupName = 获取当前图层组名称();
if (groupName !== null) {
app.preferences.rulerUnits = Units.PIXELS;
var splitGroupName = groupName.split("-");
var firstPart = splitGroupName[0];
} else {
// 如果未获取到当前图层组名称,退出程序
// alert("未获取到当前图层组名称!");
return;
}
try {
当前花样图层 = app.activeDocument.layers.getByName(firstPart);
} catch (e) {
// 处理异常情况
alert("没有找到对应的花样裁片: ");
return; // 中断函数执行
}
app.activeDocument.activeLayer = 当前花样图层;
切换mask();
载入选区蒙版()
// 应用图层蒙版();
// 载入选区();
var 边距 = 获取当前选区四边距();
var 获取左右的中心坐标 = (边距.right - 边距.left) / 2 + 边距.left;
var 获取右上的坐标 = 边距.right
$.writeln("中心坐标=" + 获取左右的中心坐标);
var currentDocument = app.activeDocument;
var height = currentDocument.height.value;
var 上边距新 = 0;
var 左边距新 = 获取右上的坐标-1 ;
var 下边距新 = height;
var 右边距新 = 获取右上的坐标 + 1;
var 边距 = 获取当前选区四边距();
$.writeln("上边距:" + 边距.top);
$.writeln("左边距:" + 边距.left);
$.writeln("下边距:" + 边距.bottom);
$.writeln("右边距:" + 边距.right);
//历史记录回退领口函数();
新建选区(上边距新, 左边距新, 下边距新, 右边距新);
app.activeDocument.activeLayer = 当前花样图层;
切换mask();
选区减去();
获取右上的坐标 = 获取当前选区四边距();
获取右上的坐标y坐标信息 = 获取右上的坐标.bottom; //////////////////////以上的是获取花样的的中心坐标信息
获取右上的坐标x坐标信息 = 获取右上的坐标.left;
// $.writeln("居中领口y坐标信息" + 获取到花样图层当前居中领口y坐标信息);
//$.writeln("居中领口x坐标信息" + 获取到花样图层当前居中领口x坐标信息);
//////////////////////以上的是获取花样的的中心坐标信息
var currentDocument = app.activeDocument;
var targetLayerSet = currentDocument.layerSets.getByName(groupName);
if (targetLayerSet) {
var layers = targetLayerSet.layers;
if (layers.length > 0) {
for (var i = 0; i < layers.length; i++) {
var layer = layers[i];
var 裁片图层 = layer.name;
$.writeln("裁片图层坐标信息=" + 裁片图层);
try {
var 当前裁片图层 = app.activeDocument.layerSets.getByName(groupName).layers.getByName(裁片图层);
} catch (e) {
// 处理异常情况
alert("没有找到对应的花样裁片 " );
return; // 中断函数执行
}
app.activeDocument.activeLayer = 当前裁片图层;
载入选区11()
//var selectedLayer = app.activeDocument.activeLayer;
// var bounds = selectedLayer.bounds;
/*
图层上边距新 = 0;
图层左边距新 = 右right ;
图层下边距新 = height;
图层右边距新 = 右right +1;
左left = bounds[0].value;
上top = bounds[1].value;
右right = bounds[2].value;
下bottom = bounds[3].value;
中心坐标centerX = (bounds[2].value - bounds[0].value) / 2 + bounds[0].value;
中心坐标centerY = (bounds[3].value - bounds[1].value) / 2 + bounds[1].value;
*/
// $.writeln("中心坐标centerX" + 中心坐标centerX);
// $.writeln("中心坐标centerY" +中心坐标cent*erY);
获取花样右上的坐标裁片位置坐标 = 获取当前选区四边距();
图层上边距新 = 0;
图层左边距新 = 获取花样右上的坐标裁片位置坐标.right-1 ;
图层下边距新 = height;
图层右边距新 = 获取花样右上的坐标裁片位置坐标.right +1;
新建选区(图层上边距新, 图层左边距新, 图层下边距新, 图层右边距新);
app.activeDocument.activeLayer = 当前裁片图层;
载入选区交叉图层()
获取右上的坐标裁片位置坐标 = 获取当前选区四边距();
获取右上的坐标裁片位置坐标x=获取右上的坐标裁片位置坐标.left
获取右上的坐标裁片位置坐标y=获取右上的坐标裁片位置坐标.bottom
位移距离PXy = 获取右上的坐标y坐标信息 - 获取右上的坐标裁片位置坐标y;
位移距离PXx = 获取右上的坐标x坐标信息 - 获取右上的坐标裁片位置坐标x;
$.writeln(位移距离PXy);
$.writeln(位移距离PXx);
取消选择()
自由变换2(位移距离PXy,位移距离PXx)
//alert("移动")
}
}
}
取消选择();
}
function 获取当前图层组名称() {
var currentDocument = app.activeDocument;
var currentLayer = currentDocument.activeLayer;
if (currentLayer.typename === "LayerSet") {
var groupName = currentLayer.name;
return groupName;
} else {
alert("当前图层不是图层组。");
return null;
}
}
function 载入选区交叉图层() //载入选区
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("channel"), stringIDToTypeID("channel"), stringIDToTypeID("transparencyEnum"));
d.putReference(stringIDToTypeID("null"), r);
var r1 = new ActionReference();
r1.putProperty(stringIDToTypeID("channel"), stringIDToTypeID("selection"));
d.putReference(stringIDToTypeID("with"), r1);
executeAction(charIDToTypeID("Intr"), d, DialogModes.NO);
}
function 载入选区蒙版() //载入选区
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("channel"), stringIDToTypeID("selection"));
d.putReference(stringIDToTypeID("null"), r);
var r1 = new ActionReference();
r1.putEnumerated(stringIDToTypeID("channel"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("to"), r1);
executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
}
function 遍历图层组内的图层(图层组名称) {
var currentDocument = app.activeDocument;
var targetLayerSet = currentDocument.layerSets.getByName(图层组名称);
if (targetLayerSet) {
var layers = targetLayerSet.layers;
if (layers.length > 0) {
for (var i = 0; i < layers.length; i++) {
var layer = layers[i];
// 在这里对每个图层进行进一步的操作
$.writeln("图层名称:" + layer.name);
}
} else {
$.writeln("图层组中没有任何图层。");
}
} else {
$.writeln("找不到指定名称的图层组。");
}
}
function 新建选区(上边距, 左边距, 下边距, 右边距) {
var currentDocument = app.activeDocument;
var top = 上边距;
var left = 左边距;
var bottom = 下边距;
var right = 右边距;
var selectionRegion = Array(Array(left, top), Array(right, top), Array(right, bottom), Array(left, bottom));
currentDocument.selection.select(selectionRegion);
}
function 选区减去() //载入选区
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("channel"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
var r1 = new ActionReference();
r1.putProperty(stringIDToTypeID("channel"), stringIDToTypeID("selection"));
d.putReference(stringIDToTypeID("with"), r1);
executeAction(charIDToTypeID("Intr"), d, DialogModes.NO);
}
// 将像素转换为毫米
function pixelsToMillimeters(pixels) {
// 获取当前文档
var doc = app.activeDocument;
// 获取图像的分辨率(像素/英寸)
var resolution = doc.resolution;
// 计算像素转换为毫米
var inches = pixels / resolution;
var millimeters = inches * 25.4;
return millimeters.toFixed(2); // 保留两位小数
}
function 切换mask() //
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("channel"), stringIDToTypeID("channel"), stringIDToTypeID("mask"));
d.putReference(stringIDToTypeID("null"), r);
d.putBoolean(stringIDToTypeID("makeVisible"), false);
executeAction(stringIDToTypeID("select"), d, DialogModes.NO);
}
function 获取当前选区四边距() {
var currentDocument = app.activeDocument;
var selectionBounds = currentDocument.selection.bounds;
var top = selectionBounds[1].value;
var left = selectionBounds[0].value;
var bottom = selectionBounds[3].value;
var right = selectionBounds[2].value;
return {
top: top,
left: left,
bottom: bottom,
right: right
};
}
function 获取当前文档四边距() {
var currentDocument = app.activeDocument;
var documentBounds = currentDocument.bounds;
var top = documentBounds[1].value;
var left = documentBounds[0].value;
var bottom = documentBounds[3].value;
var right = documentBounds[2].value;
return {
top: top,
left: left,
bottom: bottom,
right: right
};
}
function 选区减去2() //
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("channel"), stringIDToTypeID("channel"), stringIDToTypeID("transparencyEnum"));
d.putReference(stringIDToTypeID("null"), r);
var r1 = new ActionReference();
r1.putProperty(stringIDToTypeID("channel"), stringIDToTypeID("selection"));
d.putReference(stringIDToTypeID("with"), r1);
executeAction(charIDToTypeID("Intr"), d, DialogModes.NO);
}
function 遍历图层组内的图层(图层组名称) {
var currentDocument = app.activeDocument;
var targetLayerSet = currentDocument.layerSets.getByName(图层组名称);
if (targetLayerSet) {
var layers = targetLayerSet.layers;
if (layers.length > 0) {
for (var i = 0; i < layers.length; i++) {
var layer = layers[i];
// 在这里对每个图层进行进一步的操作
$.writeln("图层名称:" + layer.name);
}
} else {
$.writeln("图层组中没有任何图层。");
}
} else {
$.writeln("找不到指定名称的图层组。");
}
}
function 自由变换2(位移距离PXy,位移距离PXx) //自由变换
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
d.putEnumerated(stringIDToTypeID("freeTransformCenterState"), stringIDToTypeID("quadCenterState"), stringIDToTypeID("QCSAverage"));
var d1 = new ActionDescriptor();
d1.putUnitDouble(stringIDToTypeID("horizontal"), stringIDToTypeID("pixelsUnit"), 位移距离PXx);
d1.putUnitDouble(stringIDToTypeID("vertical"), stringIDToTypeID("pixelsUnit"), 位移距离PXy);
d.putObject(stringIDToTypeID("offset"), stringIDToTypeID("offset"), d1);
d.putBoolean(stringIDToTypeID("linked"), true);
d.putEnumerated(charIDToTypeID("Intr"), stringIDToTypeID("interpolationType"), stringIDToTypeID("nearestNeighbor"));
executeAction(stringIDToTypeID("transform"), d, DialogModes.NO);
}
function 历史记录回退领口函数() //
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putOffset(stringIDToTypeID("historyState"), -2 );
d.putReference(stringIDToTypeID("null"), r);
executeAction(stringIDToTypeID("select"), d, DialogModes.NO);
}
function 取消选择() //取消选择
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("channel"), stringIDToTypeID("selection"));
d.putReference(stringIDToTypeID("null"), r);
d.putEnumerated(stringIDToTypeID("to"), stringIDToTypeID("ordinal"), stringIDToTypeID("none"));
executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
}
function 历史记录回退1领口函数() //
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putOffset(stringIDToTypeID("historyState"), -1 );
d.putReference(stringIDToTypeID("null"), r);
executeAction(stringIDToTypeID("select"), d, DialogModes.NO);
}
function 载入选区11() //载入选区
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("channel"), stringIDToTypeID("selection"));
d.putReference(stringIDToTypeID("null"), r);
var r1 = new ActionReference();
r1.putEnumerated(stringIDToTypeID("channel"), stringIDToTypeID("channel"), stringIDToTypeID("transparencyEnum"));
d.putReference(stringIDToTypeID("to"), r1);
executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
}
function 取消选择() //取消选择
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("channel"), stringIDToTypeID("selection"));
d.putReference(stringIDToTypeID("null"), r);
d.putEnumerated(stringIDToTypeID("to"), stringIDToTypeID("ordinal"), stringIDToTypeID("none"));
executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
}
"""

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,983 @@
dxf9_jscode = """
function 裁片射出比例缩放按中心点() {
app.preferences.rulerUnits = Units.PIXELS
var 主文档 = app.activeDocument;
var 主文档名称 = 主文档.name;
// 遍历当前打开的文档
for (var i = 0; i < app.documents.length; i++) {
var document = app.documents[i];
var documentName = document.name;
// 判断文档名称是否与主文档名称不相同
if (documentName !== 主文档名称) {
app.activeDocument = document;
遍历图层();
}
}
function 遍历图层() {
var layerNames = []; // 用于存储图层名称的数组
var currentDocument = app.activeDocument;
for (var j = 0; j < currentDocument.layers.length; j++) {
var layer = currentDocument.layers[j];
var layerName = layer.name;
layerNames.push(layerName);
}
// 逐个处理图层
for (var k = 0; k < layerNames.length; k++) {
var 当前图层名称 = layerNames[k];
// $.writeln("图层名称:" + 当前图层名称);
// alert(当前图层名称);
var parts = 当前图层名称.split("-");
if (parts.length > 0) {
var 裁片名称 = parts[0];
app.activeDocument = 主文档;
$.writeln(裁片名称);
初始化模板裁片名称 = 当前图层名称.split("-");
初始化码数裁片名称 = 当前图层名称.split("_");
大货组名称 =初始化模板裁片名称[0]+("-大货裁片")
实际裁片名称 = 初始化模板裁片名称[0]+"-"+初始化码数裁片名称[2]
$.writeln(大货组名称);
$.writeln(实际裁片名称);
var 空白裁片模板 = app.activeDocument.layerSets.getByName(大货组名称).layers.getByName(实际裁片名称 );
app.activeDocument.activeLayer = 空白裁片模板;
载入选区()
var 边距 = 获取当前选区四边距();
var 当前选区高度=边距.bottom-边距.top
var 当前选区宽度=边距.right-边距.left
var 高度转毫米 = pixelsToMillimeters(当前选区高度);
var 宽度转毫米 = pixelsToMillimeters(当前选区宽度);
var 搜索词 = 裁片名称;
var 匹配图层数组 = 匹配图层名(搜索词);
// 显示匹配的图层列表
if (匹配图层数组.length > 0) {
var 图层列表文本 = "匹配的图层列表:";
for (var i = 0; i < 匹配图层数组.length; i++) {
if (i !== 0) {
图层列表文本 += " ";
}
图层列表文本 += 匹配图层数组[i].name;
}
var 数据解析分割=图层列表文本.split("_");
//var 实际套花名称=名称部分[0]
var 基码图层宽度 = parseFloat(数据解析分割[1]);
var 基码图层高度 = parseFloat(数据解析分割[2]);
var 缩放比例高度=高度转毫米/基码图层高度*100
var 缩放比例宽度=宽度转毫米/基码图层宽度*100
// alert(基码图层宽度);
} else {
alert("没有找到匹配的图层。");
}
/*
$.writeln("上边距:" + 边距.top);
$.writeln("左边距:" + 边距.left);
$.writeln("下边距:" + 边距.bottom);
$.writeln("右边距:" + 边距.right);
*/8
// 示例用法:
var 毫米 = 300;
var 每英寸像素数 = app.activeDocument.resolution; // 获取当前文档的分辨率(每英寸像素数)
var 扩展像素 = 毫米转像素(毫米, 每英寸像素数);
var 裁切上边距= 边距.top-扩展像素
var 裁切左边距= 边距.left-扩展像素
var 裁切下边距= 边距.bottom+扩展像素
var 裁切右边距= 边距.right+扩展像素
$.writeln(裁切上边距);
$.writeln(裁切左边距);
$.writeln(裁切下边距);
$.writeln(裁切右边距);
裁切图层(裁切上边距,裁切左边距,裁切下边距,裁切右边距)
var 空白裁片模板 = app.activeDocument.layerSets.getByName(大货组名称).layers.getByName(实际裁片名称 );
app.activeDocument.activeLayer = 空白裁片模板;
载入选区()
var 缩放定位点的中心坐标=获取当前缩放定位点选区四边距()
var 缩放定位点的Y轴坐标=缩放定位点的中心坐标.top2+(缩放定位点的中心坐标.bottom2-缩放定位点的中心坐标.top2)/2
var 缩放定位点的X轴坐标=缩放定位点的中心坐标.left2+(缩放定位点的中心坐标.right2-缩放定位点的中心坐标.left2)/2
$.writeln("Y轴中心坐标"+缩放定位点的Y轴坐标);
$.writeln("X轴中心坐标"+缩放定位点的X轴坐标);
var 裁片 = app.activeDocument.layers.getByName(裁片名称);
app.activeDocument.activeLayer = 裁片
//var 空白裁片模板 = app.activeDocument.layerSets.getByName(大货组名称).layers.getByName(实际裁片名称 );
//app.activeDocument.activeLayer = 空白裁片模板;
取消选择()
图层按照缩放定位点进行宽高缩放(缩放定位点的X轴坐标,缩放定位点的Y轴坐标, 缩放比例高度)
// var 裁片 = app.activeDocument.layers.getByName(裁片名称);
// app.activeDocument.activeLayer = 裁片;
var 空白裁片模板 = app.activeDocument.layerSets.getByName(大货组名称).layers.getByName(实际裁片名称 );
app.activeDocument.activeLayer = 空白裁片模板;
载入选区()
var 裁片 = app.activeDocument.layers.getByName(裁片名称);
app.activeDocument.activeLayer = 裁片
添加图层蒙版()
应用图层蒙版()
裁片.copy();
历史记录回退()
app.activeDocument = currentDocument;
图层选择(当前图层名称);
载入选区();
粘贴图层();
取消选择();
// app.refresh();
var 裁片名称 = 当前图层名称.split("_");
if (裁片名称.length > 1) {
var 角度信息 = 裁片名称[1];
if (角度信息 === "180" || 角度信息 === "-180") {
自由变换();
} else if (角度信息 === "-90") {
逆时针90旋转()
} else if (角度信息 === "90") {
顺时针90旋转()
} else {
// 如果以上条件都不满足,则执行默认的代码
}
//历史记录回退缩放函数()
}
app.activeDocument = 主文档;
历史记录回退缩放函数()
}
}
app.activeDocument = currentDocument;
烧花线添加()//alert("当前码拍好")///////////////////////////////////这里可以填写添加烧花线函数
}
//alert("排版完成,请检查文件!!!")
app.activeDocument = 主文档;
}
// 将像素转换为毫米
function pixelsToMillimeters(pixels) {
// 获取当前文档
var doc = app.activeDocument;
// 获取图像的分辨率(像素/英寸)
var resolution = doc.resolution;
// 计算像素转换为毫米
var inches = pixels / resolution;
var millimeters = inches * 25.4;
return millimeters.toFixed(2); // 保留两位小数
}
function 顺时针90旋转() //自由变换
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
d.putEnumerated(stringIDToTypeID("freeTransformCenterState"), stringIDToTypeID("quadCenterState"), stringIDToTypeID("QCSAverage"));
var d1 = new ActionDescriptor();
d1.putUnitDouble(stringIDToTypeID("horizontal"), stringIDToTypeID("pixelsUnit"), 0);
d1.putUnitDouble(stringIDToTypeID("vertical"), stringIDToTypeID("pixelsUnit"), 0);
d.putObject(stringIDToTypeID("offset"), stringIDToTypeID("offset"), d1);
d.putUnitDouble(stringIDToTypeID("angle"), stringIDToTypeID("angleUnit"), 90);
d.putBoolean(stringIDToTypeID("linked"), true);
d.putEnumerated(charIDToTypeID("Intr"), stringIDToTypeID("interpolationType"), stringIDToTypeID("nearestNeighbor"));
executeAction(stringIDToTypeID("transform"), d, DialogModes.NO);
}
function 逆时针90旋转() //自由变换
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
d.putEnumerated(stringIDToTypeID("freeTransformCenterState"), stringIDToTypeID("quadCenterState"), stringIDToTypeID("QCSAverage"));
var d1 = new ActionDescriptor();
d1.putUnitDouble(stringIDToTypeID("horizontal"), stringIDToTypeID("pixelsUnit"), 0);
d1.putUnitDouble(stringIDToTypeID("vertical"), stringIDToTypeID("pixelsUnit"), 0);
d.putObject(stringIDToTypeID("offset"), stringIDToTypeID("offset"), d1);
d.putUnitDouble(stringIDToTypeID("angle"), stringIDToTypeID("angleUnit"), -90);
d.putBoolean(stringIDToTypeID("linked"), true);
d.putEnumerated(charIDToTypeID("Intr"), stringIDToTypeID("interpolationType"), stringIDToTypeID("nearestNeighbor"));
executeAction(stringIDToTypeID("transform"), d, DialogModes.NO);
}
function 匹配图层名(搜索词) {
// 获取指定图层组中的所有图层
function 获取组中所有图层(组) {
var 图层数组 = [];
var 图层组中图层 = 组.layers;
for (var i = 0; i < 图层组中图层.length; i++) {
var 图层 = 图层组中图层[i];
图层数组.push(图层);
if (图层.typename === "LayerSet") {
var 子图层 = 获取组中所有图层(图层);
图层数组 = 图层数组.concat(子图层);
}
}
return 图层数组;
}
// 获取指定名称的图层组
function 根据名称获取图层组(文档, 组名称) {
var 组 = null;
var 所有图层 = 文档.layers;
for (var i = 0; i < 所有图层.length; i++) {
var 图层 = 所有图层[i];
if (图层.typename === "LayerSet" && 图层.name === 组名称) {
组 = 图层;
break;
}
}
return 组;
}
var 文档 = app.activeDocument;
var 组名称 = "图层基础信息"; // 指定要匹配的图层组名称
var 组 = 根据名称获取图层组(文档, 组名称);
if (组) {
var 图层数组 = 获取组中所有图层(组);
var 模糊匹配图层数组 = [];
// 首先进行模糊匹配
for (var i = 0; i < 图层数组.length; i++) {
var 图层 = 图层数组[i];
if (图层.name.indexOf(搜索词) !== -1) {
模糊匹配图层数组.push(图层);
}
}
// 在模糊匹配结果中进行图层基础信息数组分割过滤
var 精确匹配图层数组 = [];
for (var j = 0; j < 模糊匹配图层数组.length; j++) {
var 模糊匹配图层 = 模糊匹配图层数组[j];
// 进行图层基础信息数组分割过滤
var 图层基础信息数组 = 模糊匹配图层.name.split("_"); // 假设分割符是 "_"
if (图层基础信息数组[0] === 搜索词) {
精确匹配图层数组.push(模糊匹配图层);
}
}
// 返回匹配的图层数组
return 精确匹配图层数组;
} else {
alert('未找到名为"' + 组名称 + '"的图层组。');
return [];
}
}
function 毫米转像素(毫米, 每英寸像素数) {
var 每英寸毫米数 = 25.4;
var 英寸 = 毫米 / 每英寸毫米数;
return Math.round(英寸 * 每英寸像素数);
}
function 图层按照缩放定位点进行宽高缩放(缩放定位点的X轴坐标,缩放定位点的Y轴坐标,缩放比例高度) //自由变换
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
d.putEnumerated(stringIDToTypeID("freeTransformCenterState"), stringIDToTypeID("quadCenterState"), stringIDToTypeID("QCSIndependent"));
var d1 = new ActionDescriptor();
d1.putUnitDouble(stringIDToTypeID("horizontal"), stringIDToTypeID("pixelsUnit"), 缩放定位点的X轴坐标);
d1.putUnitDouble(stringIDToTypeID("vertical"), stringIDToTypeID("pixelsUnit"), 缩放定位点的Y轴坐标);
d.putObject(stringIDToTypeID("position"), stringIDToTypeID("point"), d1);
var d2 = new ActionDescriptor();
d2.putUnitDouble(stringIDToTypeID("horizontal"), stringIDToTypeID("pixelsUnit"), 0);
d2.putUnitDouble(stringIDToTypeID("horizontal"), stringIDToTypeID("pixelsUnit"), 0);
d2.putUnitDouble(stringIDToTypeID("vertical"), stringIDToTypeID("pixelsUnit"), 0);
d.putObject(stringIDToTypeID("offset"), stringIDToTypeID("offset"), d2);
d.putUnitDouble(stringIDToTypeID("width"), stringIDToTypeID("percentUnit"), 缩放比例高度);
d.putUnitDouble(stringIDToTypeID("height"), stringIDToTypeID("percentUnit"), 缩放比例高度);
d.putEnumerated(charIDToTypeID("Intr"), stringIDToTypeID("interpolationType"), stringIDToTypeID("nearestNeighbor"));
executeAction(stringIDToTypeID("transform"), d, DialogModes.NO);
}
function 裁切图层(裁切上边距,裁切左边距,裁切下边距,裁切右边距) //
{
var d = new ActionDescriptor();
var d1 = new ActionDescriptor();
d1.putUnitDouble(stringIDToTypeID("top"), stringIDToTypeID("pixelsUnit"), 裁切上边距);
d1.putUnitDouble(stringIDToTypeID("left"), stringIDToTypeID("pixelsUnit"), 裁切左边距);
d1.putUnitDouble(stringIDToTypeID("bottom"), stringIDToTypeID("pixelsUnit"),裁切下边距);
d1.putUnitDouble(stringIDToTypeID("right"), stringIDToTypeID("pixelsUnit"), 裁切右边距);
d.putObject(stringIDToTypeID("to"), stringIDToTypeID("rectangle"), d1);
d.putUnitDouble(stringIDToTypeID("angle"), stringIDToTypeID("angleUnit"), 0);
d.putBoolean(stringIDToTypeID("delete"), true);
d.putEnumerated(stringIDToTypeID("cropAspectRatioModeKey"), stringIDToTypeID("cropAspectRatioModeClass"), stringIDToTypeID("pureAspectRatio"));
d.putBoolean(stringIDToTypeID("constrainProportions"), false);
executeAction(stringIDToTypeID("crop"), d, DialogModes.NO);
}
function 获取当前缩放定位点选区四边距() {
var currentDocument = app.activeDocument;
var selectionBounds = currentDocument.selection.bounds;
var top2 = selectionBounds[1].value;
var left2 = selectionBounds[0].value;
var bottom2 = selectionBounds[3].value;
var right2 = selectionBounds[2].value;
return {
top2: top2,
left2: left2,
bottom2: bottom2,
right2: right2
};
}
function 获取当前选区四边距() {
var currentDocument = app.activeDocument;
var selectionBounds = currentDocument.selection.bounds;
var top = selectionBounds[1].value;
var left = selectionBounds[0].value;
var bottom = selectionBounds[3].value;
var right = selectionBounds[2].value;
return {
top: top,
left: left,
bottom: bottom,
right: right
};
}
function 历史记录回退缩放函数() //
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putOffset(stringIDToTypeID("historyState"), -5 );
d.putReference(stringIDToTypeID("null"), r);
executeAction(stringIDToTypeID("select"), d, DialogModes.NO);
}
function 粘贴图层() //粘贴图层
{
var d = new ActionDescriptor();
executeAction(stringIDToTypeID("paste"), d, DialogModes.NO);
}
function 复制图层() //复制图层
{
var d = new ActionDescriptor();
executeAction(stringIDToTypeID("copyEvent"), d, DialogModes.NO);
}
function 载入选区() //载入选区
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("channel"), stringIDToTypeID("selection"));
d.putReference(stringIDToTypeID("null"), r);
var r1 = new ActionReference();
r1.putEnumerated(stringIDToTypeID("channel"), stringIDToTypeID("channel"), stringIDToTypeID("transparencyEnum"));
d.putReference(stringIDToTypeID("to"), r1);
executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
}
function 取消选择() //取消选择
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("channel"), stringIDToTypeID("selection"));
d.putReference(stringIDToTypeID("null"), r);
d.putEnumerated(stringIDToTypeID("to"), stringIDToTypeID("ordinal"), stringIDToTypeID("none"));
executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
}
function 图层选择(当前图层名称) //
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putName(stringIDToTypeID("layer"), 当前图层名称);
d.putReference(stringIDToTypeID("null"), r);
d.putBoolean(stringIDToTypeID("makeVisible"), false);
var list = new ActionList();
list.putInteger(6);
d.putList(stringIDToTypeID("layerID"), list);
executeAction(stringIDToTypeID("select"), d, DialogModes.NO);
}
function 自由变换() //自由变换
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
d.putEnumerated(stringIDToTypeID("freeTransformCenterState"), stringIDToTypeID("quadCenterState"), stringIDToTypeID("QCSAverage"));
var d1 = new ActionDescriptor();
d1.putUnitDouble(stringIDToTypeID("horizontal"), stringIDToTypeID("distanceUnit"), 0);
d1.putUnitDouble(stringIDToTypeID("vertical"), stringIDToTypeID("distanceUnit"), 0);
d.putObject(stringIDToTypeID("offset"), stringIDToTypeID("offset"), d1);
d.putUnitDouble(stringIDToTypeID("width"), stringIDToTypeID("percentUnit"), -100);
d.putUnitDouble(stringIDToTypeID("height"), stringIDToTypeID("percentUnit"), -100);
d.putBoolean(stringIDToTypeID("linked"), true);
d.putEnumerated(charIDToTypeID("Intr"), stringIDToTypeID("interpolationType"), stringIDToTypeID("nearestNeighbor"));
executeAction(stringIDToTypeID("transform"), d, DialogModes.NO);
}
function 选择上一图层() //
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("forwardEnum"));
d.putReference(stringIDToTypeID("null"), r);
d.putBoolean(stringIDToTypeID("makeVisible"), false);
var list = new ActionList();
list.putInteger(8);
d.putList(stringIDToTypeID("layerID"), list);
executeAction(stringIDToTypeID("select"), d, DialogModes.NO);
}
function 添加图层蒙版() //添加图层蒙版
{
var d = new ActionDescriptor();
d.putClass(stringIDToTypeID("new"), stringIDToTypeID("channel"));
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("channel"), stringIDToTypeID("channel"), stringIDToTypeID("mask"));
d.putReference(stringIDToTypeID("at"), r);
d.putEnumerated(stringIDToTypeID("using"), stringIDToTypeID("userMaskEnabled"), stringIDToTypeID("revealSelection"));
executeAction(stringIDToTypeID("make"), d, DialogModes.NO);
}
function 应用图层蒙版() //应用图层蒙版
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("channel"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
d.putBoolean(stringIDToTypeID("apply"), true);
executeAction(stringIDToTypeID("delete"), d, DialogModes.NO);
}
function 拼合所有蒙版() //拼合所有蒙版
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("document"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
executeAction(stringIDToTypeID("e805a6ee-6d75-4b62-b6fe-f5873b5fdf20"), d, DialogModes.NO);
}
function 选择蒙版() //选择蒙版
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("channel"), stringIDToTypeID("channel"), stringIDToTypeID("mask"));
d.putReference(stringIDToTypeID("null"), r);
d.putBoolean(stringIDToTypeID("makeVisible"), false);
executeAction(stringIDToTypeID("select"), d, DialogModes.NO);
}
function 历史记录回退() //
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putOffset(stringIDToTypeID("historyState"), -5);
d.putReference(stringIDToTypeID("null"), r);
executeAction(stringIDToTypeID("select"), d, DialogModes.NO);
}
function 烧花线添加() {
app.activeDocument.suspendHistory("烧花线添加", "烧花线()");
function 烧花线() {
// 遍历当前文档图层
var doc = app.activeDocument;
var layers = doc.layers;
var filteredLayers = [];
// 遍历图层筛选以P开头的图层
for (var i = 0; i < layers.length; i++) {
var layer = layers[i];
if (layer.name.charAt(0) === 'P') {
filteredLayers.push(layer);
}
}
空置图层()
// 输出图层名称
for (var j = 0; j < filteredLayers.length; j++) {
var filteredLayer = filteredLayers[j];
var 裁片底图名称=filteredLayer.name;
多选图层(裁片底图名称);
// alert(filteredLayer.name);
}
合并图层();
置为顶层();
画布大小();
var layer = app.activeDocument.activeLayer;
layer.name = "底图";
恢复默认颜色()
矩形选框像素点()
//色彩范围()
填充();
魔棒烧花线()
新建图层()
var layer2 = app.activeDocument.activeLayer;
layer2.name = "剪口";
扩展2();
恢复止口线默认颜色()
填充();
矩形选框准备删除()
清除();
魔棒();
扩展();
选择反向();
清除();
var 底图 = app.activeDocument.layers.getByName( "底图");
app.activeDocument.activeLayer=底图;
矩形选框准备删除()
清除();
置为底层()
图层样式()
取消选择()
function 多选图层(裁片底图名称) //
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putName(stringIDToTypeID("layer"), 裁片底图名称);
d.putReference(stringIDToTypeID("null"), r);
d.putEnumerated(stringIDToTypeID("selectionModifier"), stringIDToTypeID("selectionModifierType"), stringIDToTypeID("addToSelection"));
d.putBoolean(stringIDToTypeID("makeVisible"), false);
var list = new ActionList();
list.putInteger(4);
d.putList(stringIDToTypeID("layerID"), list);
executeAction(stringIDToTypeID("select"), d, DialogModes.NO);
}
function 空置图层() //
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
executeAction(stringIDToTypeID("selectNoLayers"), d, DialogModes.NO);
}
function 恢复止口线默认颜色() //取消选择
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("color"), stringIDToTypeID("foregroundColor"));
d.putReference(stringIDToTypeID("null"), r);
var d1 = new ActionDescriptor();
d1.putDouble(stringIDToTypeID("cyan"), 20);
d1.putDouble(stringIDToTypeID("magenta"), 0);
d1.putDouble(stringIDToTypeID("yellowColor"), 0);
d1.putDouble(stringIDToTypeID("black"), 0);
d.putObject(stringIDToTypeID("to"), stringIDToTypeID("CMYKColorClass"), d1);
d.putString(stringIDToTypeID("source"), "photoshopPicker");
executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
}
function 合并图层() //合并图层
{
var d = new ActionDescriptor();
executeAction(stringIDToTypeID("mergeLayersNew"), d, DialogModes.NO);
}
function 恢复默认颜色() //
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("color"), stringIDToTypeID("colors"));
d.putReference(stringIDToTypeID("null"), r);
executeAction(stringIDToTypeID("reset"), d, DialogModes.NO);
}
function 魔棒烧花线() //魔棒
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("channel"), stringIDToTypeID("selection"));
d.putReference(stringIDToTypeID("null"), r);
var d1 = new ActionDescriptor();
d1.putUnitDouble(stringIDToTypeID("horizontal"), stringIDToTypeID("distanceUnit"), 0);
d1.putUnitDouble(stringIDToTypeID("vertical"), stringIDToTypeID("distanceUnit"), 0);
d.putObject(stringIDToTypeID("to"), stringIDToTypeID("point"), d1);
d.putInteger(stringIDToTypeID("tolerance"), 6);
d.putBoolean(stringIDToTypeID("contiguous"), false);
executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
}
function 矩形选框像素点() //矩形选框
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("channel"), stringIDToTypeID("selection"));
d.putReference(stringIDToTypeID("null"), r);
var d1 = new ActionDescriptor();
d1.putUnitDouble(stringIDToTypeID("top"), stringIDToTypeID("distanceUnit"), 0);
d1.putUnitDouble(stringIDToTypeID("left"), stringIDToTypeID("distanceUnit"), 0);
d1.putUnitDouble(stringIDToTypeID("bottom"), stringIDToTypeID("distanceUnit"), 0.48);
d1.putUnitDouble(stringIDToTypeID("right"), stringIDToTypeID("distanceUnit"), 0.48);
d.putObject(stringIDToTypeID("to"), stringIDToTypeID("rectangle"), d1);
executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
}
function 置为底层() //置为底层
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
var r1 = new ActionReference();
r1.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("back"));
d.putReference(stringIDToTypeID("to"), r1);
executeAction(stringIDToTypeID("move"), d, DialogModes.NO);
}
function 置为顶层() //置为顶层
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
var r1 = new ActionReference();
r1.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("front"));
d.putReference(stringIDToTypeID("to"), r1);
executeAction(stringIDToTypeID("move"), d, DialogModes.NO);
}
function 色彩范围() //色彩范围
{
var d = new ActionDescriptor();
d.putInteger(stringIDToTypeID("fuzziness"), 40);
var d1 = new ActionDescriptor();
d1.putDouble(stringIDToTypeID("luminance"), 0);
d1.putDouble(stringIDToTypeID("a"), 0);
d1.putDouble(stringIDToTypeID("b"), 0);
d.putObject(stringIDToTypeID("minimum"), stringIDToTypeID("labColor"), d1);
var d2 = new ActionDescriptor();
d2.putDouble(stringIDToTypeID("luminance"), 0);
d2.putDouble(stringIDToTypeID("a"), 0);
d2.putDouble(stringIDToTypeID("b"), 0);
d.putObject(stringIDToTypeID("maximum"), stringIDToTypeID("labColor"), d2);
d.putInteger(stringIDToTypeID("colorModel"), 0);
executeAction(stringIDToTypeID("colorRange"), d, DialogModes.NO);
}
function 新建图层() //新建图层
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putClass(stringIDToTypeID("layer"));
d.putReference(stringIDToTypeID("null"), r);
d.putInteger(stringIDToTypeID("layerID"), 33);
executeAction(stringIDToTypeID("make"), d, DialogModes.NO);
}
function 扩展2() //扩展
{
var d = new ActionDescriptor();
d.putUnitDouble(stringIDToTypeID("by"), stringIDToTypeID("pixelsUnit"), 1);
d.putBoolean(stringIDToTypeID("selectionModifyEffectAtCanvasBounds"), false);
executeAction(stringIDToTypeID("expand"), d, DialogModes.NO);
}
function 填充() //填充
{
var d = new ActionDescriptor();
d.putEnumerated(stringIDToTypeID("using"), stringIDToTypeID("fillContents"), stringIDToTypeID("foregroundColor"));
d.putUnitDouble(stringIDToTypeID("opacity"), stringIDToTypeID("percentUnit"), 100);
d.putEnumerated(stringIDToTypeID("mode"), stringIDToTypeID("blendMode"), stringIDToTypeID("normal"));
executeAction(stringIDToTypeID("fill"), d, DialogModes.NO);
}
function 画布大小() //画布大小
{
var d = new ActionDescriptor();
d.putBoolean(stringIDToTypeID("relative"), true);
d.putUnitDouble(stringIDToTypeID("width"), stringIDToTypeID("distanceUnit"), 40);
d.putUnitDouble(stringIDToTypeID("height"), stringIDToTypeID("distanceUnit"), 40);
d.putEnumerated(stringIDToTypeID("horizontal"), stringIDToTypeID("horizontalLocation"), stringIDToTypeID("center"));
d.putEnumerated(stringIDToTypeID("vertical"), stringIDToTypeID("verticalLocation"), stringIDToTypeID("center"));
executeAction(stringIDToTypeID("canvasSize"), d, DialogModes.NO);
}
function 魔棒() //魔棒
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("channel"), stringIDToTypeID("selection"));
d.putReference(stringIDToTypeID("null"), r);
var d1 = new ActionDescriptor();
d1.putUnitDouble(stringIDToTypeID("horizontal"), stringIDToTypeID("pixelsUnit"), 3);
d1.putUnitDouble(stringIDToTypeID("vertical"), stringIDToTypeID("pixelsUnit"), 3);
d.putObject(stringIDToTypeID("to"), stringIDToTypeID("point"), d1);
d.putInteger(stringIDToTypeID("tolerance"), 6);
executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
}
function 矩形选框准备删除() //矩形选框
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("channel"), stringIDToTypeID("selection"));
d.putReference(stringIDToTypeID("null"), r);
var d1 = new ActionDescriptor();
d1.putUnitDouble(stringIDToTypeID("top"), stringIDToTypeID("distanceUnit"), 0);
d1.putUnitDouble(stringIDToTypeID("left"), stringIDToTypeID("distanceUnit"), 0);
d1.putUnitDouble(stringIDToTypeID("bottom"), stringIDToTypeID("distanceUnit"), 0.96);
d1.putUnitDouble(stringIDToTypeID("right"), stringIDToTypeID("distanceUnit"), 0.96);
d.putObject(stringIDToTypeID("to"), stringIDToTypeID("rectangle"), d1);
executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
}
function 扩展() //扩展
{
var d = new ActionDescriptor();
d.putUnitDouble(stringIDToTypeID("by"), stringIDToTypeID("pixelsUnit"), 25);
d.putBoolean(stringIDToTypeID("selectionModifyEffectAtCanvasBounds"), false);
executeAction(stringIDToTypeID("expand"), d, DialogModes.NO);
}
function 选择反向() //选择反向
{
var d = new ActionDescriptor();
executeAction(stringIDToTypeID("inverse"), d, DialogModes.NO);
}
function 清除() //清除
{
app.activeDocument.selection.clear();
}
function 图层样式() //图层样式
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("property"), stringIDToTypeID("layerEffects"));
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
d.putReference(stringIDToTypeID("null"), r);
var d1 = new ActionDescriptor();
d1.putUnitDouble(stringIDToTypeID("scale"), stringIDToTypeID("percentUnit"), 12);
var d2 = new ActionDescriptor();
d2.putBoolean(stringIDToTypeID("enabled"), true);
d2.putBoolean(stringIDToTypeID("present"), true);
d2.putBoolean(stringIDToTypeID("showInDialog"), true);
d2.putEnumerated(stringIDToTypeID("style"), stringIDToTypeID("frameStyle"), stringIDToTypeID("outsetFrame"));
d2.putEnumerated(stringIDToTypeID("paintType"), stringIDToTypeID("frameFill"), stringIDToTypeID("solidColor"));
d2.putEnumerated(stringIDToTypeID("mode"), stringIDToTypeID("blendMode"), stringIDToTypeID("normal"));
d2.putUnitDouble(stringIDToTypeID("opacity"), stringIDToTypeID("percentUnit"), 100);
d2.putUnitDouble(stringIDToTypeID("size"), stringIDToTypeID("pixelsUnit"), 16);
var d3 = new ActionDescriptor();
d3.putDouble(stringIDToTypeID("red"), 255);
d3.putDouble(stringIDToTypeID("green"), 0);
d3.putDouble(stringIDToTypeID("blue"), 0);
d2.putObject(stringIDToTypeID("color"), stringIDToTypeID("RGBColor"), d3);
d2.putBoolean(stringIDToTypeID("overprint"), false);
d1.putObject(stringIDToTypeID("frameFX"), stringIDToTypeID("frameFX"), d2);
d.putObject(stringIDToTypeID("to"), stringIDToTypeID("layerEffects"), d1);
executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
}
function 取消选择() //取消选择
{
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("channel"), stringIDToTypeID("selection"));
d.putReference(stringIDToTypeID("null"), r);
d.putEnumerated(stringIDToTypeID("to"), stringIDToTypeID("ordinal"), stringIDToTypeID("none"));
executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
}
}
}
"""

View File

@@ -0,0 +1,326 @@
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QSpinBox, QFormLayout, QTabWidget, QPushButton, QLabel, QVBoxLayout, QWidget, QHBoxLayout, QGroupBox, QLineEdit, QCheckBox, QMessageBox
from PyQt5.QtGui import QIcon
import piece_decorative
import re
from PyQt5.QtWidgets import QApplication
class ImportPDFDialog(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('Import Multiple PDF pages')
self.setWindowIcon(QIcon('icon.png'))
main_widget = QWidget()
self.setCentralWidget(main_widget)
main_layout = QVBoxLayout()
main_widget.setLayout(main_layout)
psd_group = QGroupBox('PSD裁片预处理')
psd_layout = QVBoxLayout(psd_group)
self.spin_box = QSpinBox()
self.spin_box.setMinimum(0)
self.spin_box.setMaximum(100)
self.spin_box.setValue(1)
psd_layout.addWidget(self.spin_box)
self.number_button = QPushButton('名称赋予')
self.number_button.clicked.connect(self.number_button_clicked)
psd_layout.addWidget(self.number_button)
form_layout = QFormLayout()
# fabric_break_button = QPushButton('设置裁片组')
# fabric_break_button.clicked.connect(self.break_fabric_line)
# psd_layout.addWidget(fabric_break_button)
# self.shrink_width_line_edit = QLineEdit()
# form_layout.addRow('缩水值宽:', self.shrink_width_line_edit)
# self.shrink_height_line_edit = QLineEdit()
# form_layout.addRow('缩水值高:', self.shrink_height_line_edit)
#
# psd_layout.addLayout(form_layout)
# psd_pattern_button = QPushButton('缩水修改')
# psd_pattern_button.clicked.connect(self.set_psd_pattern)
# psd_layout.addWidget(psd_pattern_button)
psd_place_button = QPushButton('角度校准')
psd_place_button.clicked.connect(self.place_psd_pieces)
psd_layout.addWidget(psd_place_button)
psdcut_grab_button = QPushButton('花样裁切')
psdcut_grab_button.clicked.connect(self.psdcut)
psd_layout.addWidget(psdcut_grab_button)
psd_grab_button = QPushButton('裁片抓取')
psd_grab_button.clicked.connect(self.grab_psd_pieces)
psd_layout.addWidget(psd_grab_button)
main_layout.addWidget(psd_group)
psd_group2 = QGroupBox('缩水修改')
psd_layout = QVBoxLayout(psd_group2)
# self.spin_box = QSpinBox()
# self.spin_box.setMinimum(0)
# self.spin_box.setMaximum(100)
# self.spin_box.setValue(1)
# psd_layout.addWidget(self.spin_box)
# self.number_button = QPushButton('名称赋予')
# self.number_button.clicked.connect(self.number_button_clicked)
# psd_layout.addWidget(self.number_button)
# form_layout = QFormLayout()
# fabric_break_button = QPushButton('设置裁片组')
# fabric_break_button.clicked.connect(self.break_fabric_line)
# psd_layout.addWidget(fabric_break_button)
self.shrink_width_line_edit = QLineEdit()
form_layout.addRow('缩水值宽:', self.shrink_width_line_edit)
self.shrink_height_line_edit = QLineEdit()
form_layout.addRow('缩水值高:', self.shrink_height_line_edit)
psd_layout.addLayout(form_layout)
psd_pattern_button = QPushButton('缩水修改')
psd_pattern_button.clicked.connect(self.set_psd_pattern)
psd_layout.addWidget(psd_pattern_button)
# psd_place_button = QPushButton('角度校准')
# psd_place_button.clicked.connect(self.place_psd_pieces)
# psd_layout.addWidget(psd_place_button)
# psdcut_grab_button = QPushButton('花样裁切')
# psdcut_grab_button.clicked.connect(self.psdcut)
# psd_layout.addWidget(psdcut_grab_button)
# psd_grab_button = QPushButton('裁片抓取')
# psd_grab_button.clicked.connect(self.grab_psd_pieces)
# psd_layout.addWidget(psd_grab_button)
main_layout.addWidget(psd_group2)
# 添加六个按钮,每行三个按钮
align_group = QGroupBox('裁片对齐')
align_layout = QVBoxLayout(align_group)
# 创建水平布局用于放置每行的按钮
row_layout = QHBoxLayout()
# 创建第一个按钮
neckline_align_button = QPushButton('左上对齐')
neckline_align_button.clicked.connect(self.align_neckline1)
row_layout.addWidget(neckline_align_button)
# 创建第二个按钮
button2 = QPushButton('领口对齐')
button2.clicked.connect(self.another_function2)
row_layout.addWidget(button2)
# 创建第三个按钮
button3 = QPushButton('右上对齐')
button3.clicked.connect(self.another_function3)
row_layout.addWidget(button3)
# 将第一行按钮添加到垂直布局
align_layout.addLayout(row_layout)
# 创建水平布局用于放置第二行的按钮
row_layout = QHBoxLayout()
# 创建第四个按钮
button4 = QPushButton('左下对齐')
button4.clicked.connect(self.another_function4)
row_layout.addWidget(button4)
# 创建第五个按钮
button5 = QPushButton('下摆对齐')
button5.clicked.connect(self.another_function5)
row_layout.addWidget(button5)
# 创建第六个按钮
button6 = QPushButton('右下对齐')
button6.clicked.connect(self.another_function6)
row_layout.addWidget(button6)
# 将第二行按钮添加到垂直布局
align_layout.addLayout(row_layout)
main_layout.addWidget(align_group)
main_layout.addWidget(align_group)
info_group = QGroupBox('信息写入')
info_layout = QVBoxLayout(info_group)
size_add_button = QPushButton('添加定位点')
size_add_button.clicked.connect(self.add_sizes)
info_layout.addWidget(size_add_button)
# material_count_button = QPushButton('缩放信息写入')
# material_count_button.clicked.connect(self.count_materials)
# info_layout.addWidget(material_count_button)
material_count_button2 = QPushButton('重写缩放信息')
material_count_button2.clicked.connect(self.count_materials2)
info_layout.addWidget(material_count_button2)
main_layout.addWidget(info_group)
pattern_group = QGroupBox('自动套花')
pattern_layout = QVBoxLayout(pattern_group)
pattern_extend_button = QPushButton('通码延申')
pattern_extend_button.clicked.connect(self.extend_pattern)
pattern_layout.addWidget(pattern_extend_button)
scale_button = QPushButton('宽高缩放')
scale_button.clicked.connect(self.scale_dimensions)
pattern_layout.addWidget(scale_button)
proportional_scale_button = QPushButton('比例缩放')
proportional_scale_button.clicked.connect(self.proportional_scale)
pattern_layout.addWidget(proportional_scale_button)
bigproportional_scale_button = QPushButton('定位点比例缩放')
bigproportional_scale_button.clicked.connect(self.bigproportional_scale)
pattern_layout.addWidget(bigproportional_scale_button)
# self.checkbox1 = QCheckBox('混排套图方法', self)
# pattern_layout.addWidget(self.checkbox1)
main_layout.addWidget(pattern_group)
save_group = QGroupBox('文档保存')
save_layout = QVBoxLayout(save_group)
# add_size_button = QPushButton('尺码激活')
# add_size_button.clicked.connect(self.add_size_to_layers)
# save_layout.addWidget(add_size_button)
form_layout = QFormLayout()
self.prefix_line_edit = QLineEdit()
form_layout.addRow('前缀添加:', self.prefix_line_edit)
save_layout.addLayout(form_layout)
save_button = QPushButton('保存')
save_button.clicked.connect(self.save_document2)
save_layout.addWidget(save_button)
main_layout.addWidget(save_group)
def align_neckline1(self):
piece_decorative.PS_DXF7_jscode_fun('左上对齐2()')
pass
def another_function2(self):
piece_decorative.PS_DXF3_jscode_fun('领口对齐2()')
pass
def another_function3(self):
piece_decorative.PS_DXF2_jscode_fun('右上对齐2()')
# piece_decorative.PS_DXF2_jscode_fun(f'文档保存最新("{前缀}");')
pass
def another_function4(self):
piece_decorative.PS_DXF4_jscode_fun('左下对齐2()')
# piece_decorative.PS_DXF2_jscode_fun(f'文档保存最新("{前缀}");')
pass
def another_function5(self):
piece_decorative.PS_DXF5_jscode_fun('下摆对齐2()')
# piece_decorative.PS_DXF2_jscode_fun(f'文档保存最新("{前缀}");')
pass
def another_function6(self):
piece_decorative.PS_DXF6_jscode_fun('右下对齐2()')
# piece_decorative.PS_DXF2_jscode_fun(f'文档保存最新("{前缀}");')
pass
def save_document2(self):
前缀 = self.prefix_line_edit.text()
piece_decorative.PS_DXF2_jscode_fun(f'文档保存最新("{前缀}");')
def add_size_to_layers(self):
piece_decorative.PS_DXF2_jscode_fun('信息激活2();')
def psdcut(self):
piece_decorative.PS_DXF6_jscode_fun('图像切割2();')
def number_button_clicked(self):
current_value = self.spin_box.value()
piece_decorative.PS_DXF_jscode_fun(f"名称赋予({current_value});")
new_value = current_value + 1
self.spin_box.setValue(new_value)
def another_function(self):
# 在这里定义按钮点击事件的处理逻辑
pass
def set_psd_pattern(self):
高度值 = self.shrink_height_line_edit.text()
宽度值 = self.shrink_width_line_edit.text()
number_pattern = re.compile(r'^\d+(\.\d+)?$') # 正则表达式匹配数字格式
if number_pattern.match(高度值) and number_pattern.match(宽度值):
# 如果两个值都是数字,执行批量缩水操作
# piece_decorative.PS_DXF2_jscode_fun('设置花样组删除图层设置名称();')
piece_decorative.PS_DXF2_jscode_fun(f"批量缩水值修改({宽度值},{高度值});")
else:
# 如果至少有一个值不是数字,显示警告
QMessageBox.warning(self, '错误', '缩水值只能是数字!')
def grab_psd_pieces(self):
piece_decorative.PS_DXF2_jscode_fun('设置花样组删除图层设置名称();')
piece_decorative.PS_DXF12_jscode_fun('批量套数写入();')
piece_decorative.PS_DXF2_jscode_fun('设置花样组2();')
piece_decorative.PS_DXF_jscode_fun('裁片吸取2();')
piece_decorative.PS_DXF2_jscode_fun('设置花样组顺序居中();')
piece_decorative.PS_DXF_jscode_fun('信息写入();')
piece_decorative.PS_DXF3_jscode_fun('裁片视图检查2();')
def place_psd_pieces(self):
piece_decorative.PS_DXF3_jscode_fun('角度旋转();')
def align_neckline(self):
piece_decorative.PS_DXF2_jscode_fun('领口对齐();')
def extend_pattern(self):
# if self.checkbox1.isChecked():
# piece_decorative.PS_DXF_jscode_fun('删除指定名称蒙版();')
# piece_decorative.PS_DXF20_jscode_fun('混排通码延申导出();')
# print('按下')
#
# else:
# print('没有按下')
piece_decorative.PS_DXF6_jscode_fun('前景色修改();')
piece_decorative.PS_DXF_jscode_fun('删除指定名称蒙版();')
piece_decorative.PS_DXF_jscode_fun('裁片射出();')
piece_decorative.PS_DXF2_jscode_fun('信息激活2();')
def scale_dimensions(self):
piece_decorative.PS_DXF6_jscode_fun('前景色修改();')
piece_decorative.PS_DXF_jscode_fun('删除指定名称蒙版();')
piece_decorative.PS_DXF3_jscode_fun('裁片射出宽高缩放();')
piece_decorative.PS_DXF2_jscode_fun('信息激活2();')
def proportional_scale(self):
piece_decorative.PS_DXF6_jscode_fun('前景色修改();')
piece_decorative.PS_DXF_jscode_fun('删除指定名称蒙版();')
piece_decorative.PS_DXF9_jscode_fun('裁片射出比例缩放按中心点();')
piece_decorative.PS_DXF2_jscode_fun('信息激活2();')
def bigproportional_scale(self):
piece_decorative.PS_DXF6_jscode_fun('前景色修改();')
piece_decorative.PS_DXF_jscode_fun('删除指定名称蒙版();')
piece_decorative.PS_DXF11_jscode_fun('裁片射出缩放();')
piece_decorative.PS_DXF2_jscode_fun('信息激活2();')
def add_sizes(self):
piece_decorative.PS_DXF_jscode_fun('添加缩放定位点();')
def count_materials(self):
piece_decorative.PS_DXF_jscode_fun('信息写入();')
def count_materials2(self):
piece_decorative.PS_DXF3_jscode_fun('重写基码信息2();')
piece_decorative.PS_DXF_jscode_fun('信息写入();')
if __name__ == '__main__':
app2 = QApplication(sys.argv)
dialog = ImportPDFDialog()
dialog.show()
sys.exit(app2.exec_())

View File

@@ -0,0 +1,427 @@
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QLabel, QPushButton, QFileDialog, \
QLineEdit, QScrollArea, QGroupBox, QHBoxLayout, QMessageBox, QProgressDialog
from PyQt5.QtGui import QIntValidator
from PyQt5.QtCore import QTimer
import re
import os
import ezdxf
import ezdxf.tools
import ezdxf.bbox
import ezdxf.units
import ezdxf.math
from coreldraw_checker import is_coreldraw_running
from functools import partial
import win32com.client
import os
import shutil
import threading
from clear_folder import another_function
class YourMainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("RUNDXF")
layout = QVBoxLayout()
self.button1 = QPushButton("DXF文件路径")
self.button1.setFixedWidth(200)
self.button1.clicked.connect(self.showDxfFileDialog)
self.button2 = QPushButton("PLT文件路径")
self.button2.setFixedWidth(200)
self.button2.clicked.connect(self.showPltFileDialog)
self.initial_button1_text = self.button1.text()
self.initial_button2_text = self.button2.text()
panel1 = QGroupBox("文件路径")
panel1_layout = QVBoxLayout(panel1)
panel1_layout.setSpacing(10)
panel1_layout.setContentsMargins(10, 10, 10, 10)
panel1_layout.addWidget(self.button1)
panel1_layout.addWidget(self.button2)
layout.addWidget(panel1)
self.label5 = QLabel('单码片数')
self.lineEdit3 = QLineEdit()
self.lineEdit3.setValidator(QIntValidator())
self.lineEdit3.setFixedSize(120, 30)
layout.addWidget(self.label5)
layout.addWidget(self.lineEdit3)
self.scrollWidget = QWidget()
self.scrollWidgetLayout = QVBoxLayout(self.scrollWidget)
self.scrollArea = QScrollArea()
self.scrollArea.setWidget(self.scrollWidget)
self.scrollArea.setWidgetResizable(True)
layout.addWidget(self.scrollArea)
self.clearButton = QPushButton("清空信息")
self.clearButton.clicked.connect(self.clearScrollArea)
layout.addWidget(self.clearButton)
confirm_button = QPushButton("分割")
confirm_button.clicked.connect(self.updateScrollArea)
#confirm_button.clicked.connect(self.freezeAndParse) # 连接按钮点击事件
layout.addWidget(confirm_button)
central_widget = QWidget()
central_widget.setLayout(layout)
self.setCentralWidget(central_widget)
self.dxfLineEdits = {}
self.allowButtonActions = True # 标志变量,控制是否允许按钮行为
def run_coreldraw_macros(self):
try:
dogms = win32com.client.DispatchEx("CorelDRAW.Application.23")
macros_to_run = [
"RUN.OpenDXFFilesInFolder",
"RUN.RotateSelectionClockwise",
"RUN.DeleteUnnamedSublayers",
"RUN.StToFront",
"RUN.IterateSublayerNames",
]
for macro in macros_to_run:
dogms.GMSManager.RunMacro("RUNDXF", macro)
except Exception as e:
QMessageBox.warning(self, "警告", "缺少CDR模块请载入CDR模块", QMessageBox.Ok)
# print("缺少CDR模块请载入CDR模块")
def showPltFileDialog(self):
options = QFileDialog.Options()
file_path, _ = QFileDialog.getOpenFileName(self, "选择PLT文件", "", "PLT Files (*.plt);;All Files (*)",
options=options)
if file_path:
print("Selected PLT file:", file_path)
extracted_content = self.extract_content_from_plt_path(file_path)
print(extracted_content)
self.sizes = self.fill_sizes_from_extracted_content(extracted_content)
# 更新尺寸字典后,清空并填充滚动区域
self.clearScrollArea()
self.populateScrollArea()
self.initial_plt_path = file_path # 更新初始路径而不更新按钮文本
else:
print("No PLT file selected")
QMessageBox.warning(self, "警告", "没有选择文件夹。请重新选择文件夹。", QMessageBox.Ok)
pass
def showDxfFileDialog(self):
options = QFileDialog.Options()
file_path, _ = QFileDialog.getOpenFileName(self, "选择DXF文件", "", "DXF Files (*.dxf);;All Files (*)",
options=options)
if file_path:
print("Selected DXF file:", file_path)
self.initial_dxf_path = file_path # 更新初始路径而不更新按钮文本
else:
print("No DXF file selected")
QMessageBox.warning(self, "警告", "没有选择文件夹。请重新选择文件夹。", QMessageBox.Ok)
# 在此处添加提醒逻辑,例如使用 QMessageBox 提示用户没有选择文件
def extract_content_from_plt_path(self, plt_path):
match = re.search(r'\((.*?)\)', plt_path)
if match:
extracted_content = match.group(1)
return extracted_content
else:
return "No content in parentheses found"
def fill_sizes_from_extracted_content(self, extracted_content):
sizes = extracted_content.split("+")
size_dict = {}
for size in sizes:
size_dict[size] = ""
return size_dict
def process_dxf_file(self, file_path, extracted_content):
doc = ezdxf.readfile(file_path)
msp = doc.modelspace()
mspBox = ezdxf.bbox.extents(msp)
print("=====", os.path.basename(file_path))
print("左上角坐标:", mspBox.extmin)
print("画布宽:", mspBox.size[0], "画布高:", mspBox.size[1])
print()
for entity in msp.query():
if entity.dxftype() == "INSERT":
temp = []
rotation = None
block = doc.blocks[entity.dxf.name]
for e in block:
if e.dxftype() != "TEXT":
temp.append(e)
else:
rotation = e.dxf.rotation
if rotation is not None:
rotation %= 360
if 45 <= rotation < 135:
rotation = 90
elif 135 <= rotation < 225:
rotation = 180
elif 225 <= rotation < 315:
rotation = -90
else:
rotation = 0
print("=====", entity.dxf.name)
print("大小:", ezdxf.bbox.extents(temp).size)
print("文字角度:", rotation)
center = ezdxf.bbox.extents(temp).center
center = (center.x, mspBox.extmax.y - center.y) # 调整center y值
print("中心坐标:", center)
center = (center[1], mspBox.size[0] - center[0]) # 旋转后中心坐标
print("旋转后中心坐标:", center)
separator = "_" # 分隔符
entity.dxf.name += separator + str(rotation)
block.name += separator + str(rotation)
new_file_path = os.path.join(r"D:\marktemp", "{}.dxf".format(extracted_content))
doc.saveas(new_file_path)
def getSinglePieceCount(self):
return self.lineEdit3.text()
def recreate_folders(self):
# 定义文件夹路径
folder_paths = [r"D:\PSMARKtemp", r"D:\marktemp"]
# 删除文件夹及其内容
for folder_path in folder_paths:
if os.path.exists(folder_path):
shutil.rmtree(folder_path)
print(f"Deleted folder: {folder_path}")
# 重新创建文件夹
for folder_path in folder_paths:
os.makedirs(folder_path)
print(f"Recreated folder: {folder_path}")
def freezeAndParse(self):
self.parse_button.setEnabled(False) # 冻结按钮
QTimer.singleShot(10000, self.unfreezeButton) # 10秒后解冻按钮
def unfreezeButton(self):
self.parse_button.setEnabled(True) # 解冻按钮
def updateScrollArea(self):
another_function()
if not is_coreldraw_running():
QMessageBox.warning(self, "警告", "CorelDRAW未运行无法执行操作。")
return
plt_file_path = self.initial_plt_path
# 获取DXF文件路径
dxf_file_path = self.initial_dxf_path
extracted_content = self.extract_content_from_plt_path(plt_file_path)
if dxf_file_path:
# 去掉括号内内容后的PLT文件名作为DXF文件名
plt_filename = os.path.basename(plt_file_path)
# dxf_filename = re.sub(r'\(.*?\)', '', plt_filename)
self.process_dxf_file(dxf_file_path, extracted_content) # 调用解析函数并传入单码片数和新的DXF文件名
print("DXF文件解析完成")
else:
QMessageBox.warning(self, "警告", "没有选择DXF文件。请先选择一个DXF文件。", QMessageBox.Ok)
print()
self.run_coreldraw_macros()
single_code_pieces = int(self.getSinglePieceCount()) # 获取单码片数
print(single_code_pieces)
# 打印滚动区域中的输入框内容
code_quantities = {} # 创建一个新的字典用于存储数据
for label, line_edit in self.dxfLineEdits.items():
text = line_edit.text()
if text.isdigit():
value = int(text) # 尝试将文本转换为整数
else:
try:
value = float(text) # 尝试将文本转换为浮点数
except ValueError:
print(f"Invalid value for {label}: {text}")
continue # 转换失败,跳过当前循环迭代
code_quantities[label] = value # 存储转换后的数字到字典
print(code_quantities)
length = len(code_quantities)
print(length) # 输出 3因为字典中有三对键值对
corel_app = win32com.client.Dispatch("CorelDRAW.Application.23")
# 获取当前活动文档
active_document = corel_app.ActiveDocument
# 获取当前页面中所有图层的名称,排除特定名称的图层
layer_names = [layer.Name for layer in active_document.ActivePage.Layers
if layer.Name not in ["辅助线", "1", "0", "Defpoints"]]
p_numbers = [] # 初始化存储 P 数字的列表
for code, quantity in code_quantities.items():
for i in range(1, single_code_pieces + 1):
p_numbers.extend([f"P{i}"] * int(quantity))
print(p_numbers)
# 循环遍历不同的码
# p_numbers = [] # 初始化存储 P 数字的列表
#
# for code, quantity in code_quantities.items():
# for i in range(1, single_code_pieces + 1):
# # 根据码的数量分别生成对应数量的 P 数字,并添加到列表中
# p_numbers.extend([f"P{i}"] * quantity)
# print(p_numbers)
new_layer_names = []
index = 0
for old_name in layer_names:
parts = old_name.split("-") # 根据"-"分割字符串
if len(parts) > 1:
new_name = f"{p_numbers[index]}-{parts[1]}" # 使用数组中的 P 数字
new_layer_names.append(new_name)
index += 1
# 在新的图层名数组中遍历,对图层进行修改
modified_names = [] # 创建一个列表来存储修改后的名称
modified_names2 = []
for i, new_name in enumerate(new_layer_names):
active_document.ActivePage.Layers(layer_names[i]).Name = new_name
modified_names2.append(new_name)
modified_names.append(new_name)
print(f"Modified: {layer_names[i]} -> {new_name}")
# print(modified_names)
def delete_layers_by_names(names_to_delete, active_document):
corel_app = win32com.client.Dispatch("CorelDRAW.Application.23")
# 获取当前活动文档
active_document = corel_app.ActiveDocument
for target_layer_name in names_to_delete:
for layer in active_document.ActivePage.Layers:
if layer.Name == target_layer_name:
layer.Delete()
break # 找到目标图层后中断循环
modified_names_list = [] # 用于存储每次循环中的 modified_names 列表
Index = 0
for code in code_quantities:
quantity = code_quantities[code]
total_pieces = quantity * single_code_pieces
# 获取数组的前 total_pieces 个元素
newmodified_names_filtered = modified_names[:total_pieces]
# print(newmodified_names_filtered)
result_array = [fruit for fruit in modified_names2 if fruit not in newmodified_names_filtered]
result_array_length = len(result_array)
print(result_array_length)
delete_layers_by_names(result_array, active_document.ActivePage)
# modified_names_list.append(modified_names) # 将 modified_names 添加到数组中
dogms = win32com.client.DispatchEx("CorelDRAW.Application.23")
dogms.GMSManager.RunMacro("RUNDXF", "RUN.ExportSelectionToPSD", Index)
dogms.GMSManager.RunMacro("RUNDXF", "RUN.HOURUN", result_array_length)
modified_names = modified_names[total_pieces:]
Index += 1
corel_app = win32com.client.Dispatch("CorelDRAW.Application.23")
corel_app .GMSManager.RunMacro("RUNDXF", "RUN.ActiveDocumentClose")
QMessageBox.warning(self, "提醒", "分割完成,请进行裁片套版操作。")
def updateLineEditsFromSizes(self):
for size_label, line_edit in self.dxfLineEdits.items():
self.sizes[size_label] = line_edit.text()
def populateScrollArea(self):
self.clearScrollArea()
for size_label, size_text in self.sizes.items():
size_layout = QHBoxLayout()
size_layout.addWidget(QLabel(size_label))
line_edit = QLineEdit()
line_edit.setValidator(QIntValidator())
line_edit.setFixedSize(100, 30)
line_edit.setText(size_text)
self.dxfLineEdits[size_label] = line_edit
size_layout.addWidget(line_edit)
self.scrollWidgetLayout.addLayout(size_layout)
def clearScrollArea(self):
for i in reversed(range(self.scrollWidgetLayout.count())):
item = self.scrollWidgetLayout.itemAt(i)
if isinstance(item, QHBoxLayout) or isinstance(item, QVBoxLayout):
while item.count():
widget = item.takeAt(0).widget()
if widget:
widget.deleteLater()
self.dxfLineEdits.clear() # 清空部件引用
if __name__ == '__main__':
app = QApplication(sys.argv)
mainWindow = YourMainWindow()
mainWindow.show()
sys.exit(app.exec_())

View File

@@ -0,0 +1,311 @@
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QVBoxLayout, QPushButton, QGroupBox, QLabel, QLineEdit, QFormLayout
import piece_decorative
class ImportPDFDialog2(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('Import Multiple PDF pages')
main_widget = QWidget()
self.setCentralWidget(main_widget)
main_layout = QVBoxLayout()
main_widget.setLayout(main_layout)
new_group_box5 = QGroupBox('打版联动')
new_group_layout5 = QVBoxLayout(new_group_box5)
# 创建4个按钮并连接到槽函数
Dbtn4_1 = QPushButton('图层分割')
Dbtn4_2 = QPushButton('批量图层编组')
Dbtn4_3 = QPushButton('快速超链接')
# Dbtn4_4 = QPushButton('定位点比例缩放(模板)')
Dbtn4_1.clicked.connect(self.on_Dbtn4_1_clicked)
Dbtn4_2.clicked.connect(self.on_Dbtn4_2_clicked)
Dbtn4_3.clicked.connect(self.on_Dbtn4_3_clicked)
# Dbtn4_4.clicked.connect(self.on_Dbtn4_4_clicked)
# 将按钮添加到新的盒子1中
new_group_layout5.addWidget(Dbtn4_1)
new_group_layout5.addWidget(Dbtn4_2)
new_group_layout5.addWidget(Dbtn4_3)
# new_group_layout5.addWidget(Dbtn4_4)
# 将新的盒子1添加到主布局中
main_layout.addWidget(new_group_box5)
# 快速换图
quick_change_group = QGroupBox('快速换图')
quick_change_layout = QVBoxLayout(quick_change_group)
# bigbtn_standardize_pattern = QPushButton('图像切割')
btn_standardize_pattern = QPushButton('花样标准化')
btn_pattern_to_external = QPushButton('花样转外链')
btn_quick_change = QPushButton('快速换图')
btn_batch_quick_change = QPushButton('批量快速换图')
# btn_Kbatch_quick_change = QPushButton('特定版本快速换图')
# 为每个按钮连接槽函数
btn_standardize_pattern.clicked.connect(self.on_standardize_pattern_clicked)
btn_pattern_to_external.clicked.connect(self.on_pattern_to_external_clicked)
btn_quick_change.clicked.connect(self.on_quick_change_clicked)
btn_batch_quick_change.clicked.connect(self.on_batch_quick_change_clicked)
# btn_Kbatch_quick_change.clicked.connect(self.on_kbatch_quick_change_clicked)
# bigbtn_standardize_pattern.clicked.connect(self.on_bigstandardize_pattern_clicked)
quick_change_layout.addWidget(btn_standardize_pattern)
# quick_change_layout.addWidget(bigbtn_standardize_pattern)
quick_change_layout.addWidget(btn_pattern_to_external)
quick_change_layout.addWidget(btn_quick_change)
quick_change_layout.addWidget(btn_batch_quick_change)
# quick_change_layout.addWidget(btn_Kbatch_quick_change)
main_layout.addWidget(quick_change_group)
# 初始化界面
# 创建一个新的盒子
new_group_box1 = QGroupBox('模板生成')
new_group_layout1 = QVBoxLayout(new_group_box1)
# 创建4个按钮并连接到槽函数
btn4_1 = QPushButton('通码延申(模板)')
btn4_2 = QPushButton('宽高缩放(模板)')
btn4_3 = QPushButton('比例缩放(模板)')
btn4_4 = QPushButton('定位点比例缩放(模板)')
btn4_1.clicked.connect(self.on_btn4_1_clicked)
btn4_2.clicked.connect(self.on_btn4_2_clicked)
btn4_3.clicked.connect(self.on_btn4_3_clicked)
btn4_4.clicked.connect(self.on_btn4_4_clicked)
# 将按钮添加到新的盒子1中
new_group_layout1.addWidget(btn4_1)
new_group_layout1.addWidget(btn4_2)
new_group_layout1.addWidget(btn4_3)
new_group_layout1.addWidget(btn4_4)
# 将新的盒子1添加到主布局中
main_layout.addWidget(new_group_box1)
#############################################
new_group_box5 = QGroupBox('定位码快速换图')
new_group_layout5 = QVBoxLayout(new_group_box5)
# 创建4个按钮并连接到槽函数
Kbtn4_1 = QPushButton('定位码快速超链接')
Kbtn4_2 = QPushButton('定位码快速换图')
# Dbtn4_4 = QPushButton('定位点比例缩放(模板)')
Kbtn4_1.clicked.connect(self.on_Kbtn4_1_clicked)
Kbtn4_2.clicked.connect(self.on_Kbtn4_2_clicked)
#Dbtn4_3.clicked.connect(self.on_Dbtn4_3_clicked)
# Dbtn4_4.clicked.connect(self.on_Dbtn4_4_clicked)
# 将按钮添加到新的盒子1中
new_group_layout5.addWidget(Kbtn4_1)
new_group_layout5.addWidget(Kbtn4_2)
# new_group_layout5.addWidget(Dbtn4_3)
# new_group_layout5.addWidget(Dbtn4_4)
# 将新的盒子1添加到主布局中
main_layout.addWidget(new_group_box5)
##############################################
new_group_box2 = QGroupBox('批量化工具')
new_group_layout2 = QVBoxLayout(new_group_box2)
# 创建4个按钮并连接到槽函数
Pbtn4_1 = QPushButton('小码标添加')
Pbtn4_2 = QPushButton('批量修改分辨率')
Pbtn4_3 = QPushButton('批量加款号')
Pbtn4_4 = QPushButton('模特批量替换')
Pbtn4_5 = QPushButton('SO小样连晒')
Pbtn4_6 = QPushButton('SO小样拼贴')
Pbtn4_7 = QPushButton('SO小样缩放')
Pbtn4_1.clicked.connect(self.on_Pbtn4_1_clicked)
Pbtn4_2.clicked.connect(self.on_Pbtn4_2_clicked)
Pbtn4_3.clicked.connect(self.on_Pbtn4_3_clicked)
Pbtn4_4.clicked.connect(self.on_Pbtn4_4_clicked)
Pbtn4_5.clicked.connect(self.on_Pbtn4_5_clicked)
Pbtn4_6.clicked.connect(self.on_Pbtn4_6_clicked)
Pbtn4_7.clicked.connect(self.on_Pbtn4_7_clicked)
# 将按钮添加到新的盒子1中
new_group_layout2.addWidget(Pbtn4_1)
new_group_layout2.addWidget(Pbtn4_2)
new_group_layout2.addWidget(Pbtn4_3)
new_group_layout2.addWidget(Pbtn4_4)
new_group_layout2.addWidget(Pbtn4_5)
new_group_layout2.addWidget(Pbtn4_6)
new_group_layout2.addWidget(Pbtn4_7)
# 将新的盒子1添加到主布局中
main_layout.addWidget(new_group_box2)
# def on_kbatch_quick_change_clicked(self):
# piece_decorative.PS_DXF18_jscode_fun('龙服的快速换图();')
#
# print("按钮被点击")
# pass
def on_Pbtn4_7_clicked(self):
piece_decorative.PS_DXF27_jscode_fun('新的米样缩放();')
print("按钮被点击")
pass
def on_Kbtn4_1_clicked(self):
piece_decorative.PS_DXF16_jscode_fun('快速定位码链接();')
print("按钮被点击")
pass
def on_Kbtn4_2_clicked(self):
piece_decorative.PS_DXF17_jscode_fun('定位码批量化替换外链新();')
print("按钮被点击")
pass
def on_Dbtn4_1_clicked(self):
piece_decorative.PS_DXF8_jscode_fun('图像分割();')
print("按钮被点击")
pass
def on_Dbtn4_2_clicked(self):
piece_decorative.PS_DXF15_jscode_fun('图层自动编组2();')
print("按钮被点击")
pass
def on_Dbtn4_3_clicked(self):
piece_decorative.PS_DXF15_jscode_fun('快速超级链接2();')
# piece_decorative.PS_DXF22_jscode_fun('模特换衣功能();')
print("按钮被点击")
pass
def on_Pbtn4_4_clicked(self):
piece_decorative.PS_DXF26_jscode_fun('模特换图();')
print("按钮被点击")
pass
def on_Pbtn4_5_clicked(self):
piece_decorative.PS_DXF23_jscode_fun('自动连晒();')
print("按钮被点击")
pass
def on_Pbtn4_6_clicked(self):
piece_decorative.PS_DXF24_jscode_fun('自动米样拼贴();')
print("按钮被点击")
pass
def on_Pbtn4_1_clicked(self):
piece_decorative.PS_DXF8_jscode_fun('码标添加2();')
print("按钮被点击")
pass
def on_Pbtn4_2_clicked(self):
piece_decorative.PS_DXF8_jscode_fun('批量分辨率修改();')
print("按钮被点击")
pass
def on_Pbtn4_3_clicked(self):
piece_decorative.PS_DXF8_jscode_fun('批量款号添加();')
print("按钮被点击")
pass
# 槽函数示例
def on_standardize_pattern_clicked(self):
piece_decorative.PS_DXF5_jscode_fun('花样标准化3();')
print("花样标准化按钮被点击")
def on_pattern_to_external_clicked(self):
piece_decorative.PS_DXF5_jscode_fun('花样图层导出();')
print("花样转外链按钮被点击")
def on_quick_change_clicked(self):
piece_decorative.PS_DXF5_jscode_fun('替换外链新();')
print("快速换图按钮被点击")
def on_batch_quick_change_clicked(self):
piece_decorative.PS_DXF8_jscode_fun('批量化替换外链新();')
print("批量快速换图按钮被点击")
def on_btn4_1_clicked(self):
# 处理新盒子1中按钮4_1的点击事件
piece_decorative.PS_DXF_jscode_fun('删除指定名称蒙版();')
piece_decorative.PS_DXF5_jscode_fun('裁片射出模板();')
piece_decorative.PS_DXF2_jscode_fun('信息激活2();')
pass
def on_btn4_2_clicked(self):
# 处理新盒子1中按钮4_2的点击事件
piece_decorative.PS_DXF_jscode_fun('删除指定名称蒙版();')
piece_decorative.PS_DXF4_jscode_fun('裁片射出宽高缩放模板();')
piece_decorative.PS_DXF2_jscode_fun('信息激活2();')
pass
def on_btn4_3_clicked(self):
# 处理新盒子1中按钮4_3的点击事件
piece_decorative.PS_DXF_jscode_fun('删除指定名称蒙版();')
piece_decorative.PS_DXF14_jscode_fun('裁片射出宽高缩放模板按中心();')
piece_decorative.PS_DXF2_jscode_fun('信息激活2();')
pass
def on_btn4_4_clicked(self):
# 处理新盒子1中按钮4_3的点击事件
piece_decorative.PS_DXF_jscode_fun('删除指定名称蒙版();')
piece_decorative.PS_DXF7_jscode_fun('裁片射出缩放模板();')
piece_decorative.PS_DXF2_jscode_fun('信息激活2();')
pass
# def on_Dbtn4_1_clicked(self):
# # 处理新盒子1中按钮4_4的点击事件
# piece_decorative.PS_DXF8_jscode_fun('图像分割();')
# pass
# def on_Pbtn4_5_clicked(self):
# # 处理新盒子1中按钮4_4的点击事件
# piece_decorative.PS_DXF11_jscode_fun('批量重设画布幅宽 ();')
# pass
# def on_Pbtn4_6_clicked(self):
# # 处理新盒子1中按钮4_4的点击事件
# piece_decorative.PS_DXF11_jscode_fun('批量重设画布幅宽();')
# pass
if __name__ == '__main__':
app = QApplication(sys.argv)
dialog = ImportPDFDialog2()
dialog.show()
sys.exit(app.exec_())

View File

@@ -0,0 +1,81 @@
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QVBoxLayout, QPushButton, QGroupBox, QLabel, QFrame
from PyQt5 import QtGui
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget
from PyQt5.QtGui import QPixmap
import os
class ImportPDFDialog4(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('Import Multiple PDF pages')
main_widget = QWidget()
self.setCentralWidget(main_widget)
main_layout = QVBoxLayout()
main_widget.setLayout(main_layout)
# 快速换图
quick_change_group = QGroupBox('版本介绍')
quick_change_layout = QVBoxLayout(quick_change_group)
# 创建图像标签1并调整大小
image_label1 = QLabel()
# 获取当前脚本所在目录的绝对路径
current_directory = os.path.dirname(os.path.abspath(__file__))
# 构建相对路径
image_filename = "img/微信图片_20230906013631.jpg"
relative_path = os.path.join(current_directory, image_filename)
# 创建 QPixmap 对象
pixmap1 = QtGui.QPixmap(relative_path)
pixmap1 = pixmap1.scaledToWidth(200) # 设置宽度限制为200像素
image_label1.setPixmap(pixmap1)
quick_change_layout.addWidget(image_label1)
# 创建文本标签
text_label1 = QLabel('关注抖音查看视频教程')
text_label1.setAlignment(Qt.AlignmentFlag.AlignCenter)
quick_change_layout.addWidget(text_label1)
# 创建分隔线
divider1 = QFrame()
divider1.setFrameShape(QFrame.HLine)
quick_change_layout.addWidget(divider1)
# 创建图像标签2并调整大小
image_label2 = QLabel()
image_filename2 = "img/微信图片_20230906013548.jpg"
relative_path2 = os.path.join(current_directory, image_filename2)
# 创建另一个 QPixmap 对象,使用不同的变量名
pixmap2 = QtGui.QPixmap(relative_path2)
pixmap2 = pixmap2.scaledToWidth(200) # 设置宽度限制为200像素
image_label2.setPixmap(pixmap2)
quick_change_layout.addWidget(image_label2)
# 创建文本标签
text_label2 = QLabel('BUG提交 功能开发 使用反馈 请联系微信')
text_label2.setAlignment(Qt.AlignmentFlag.AlignCenter)
quick_change_layout.addWidget(text_label2)
# 创建分隔线
divider2 = QFrame()
divider2.setFrameShape(QFrame.HLine)
quick_change_layout.addWidget(divider2)
# 创建文本标签
text_label3 = QLabel('PS Mark 版本号1.8(2023.10.4) by:jimi')
text_label3.setAlignment(Qt.AlignmentFlag.AlignCenter)
quick_change_layout.addWidget(text_label3)
quick_change_group.setLayout(quick_change_layout)
main_layout.addWidget(quick_change_group)
if __name__ == '__main__':
app = QApplication(sys.argv)
dialog = ImportPDFDialog4()
dialog.show()
sys.exit(app.exec_())

View File

@@ -0,0 +1,449 @@
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QLabel, QPushButton, QFileDialog, \
QLineEdit, QScrollArea, QGroupBox, QHBoxLayout, QMessageBox, QProgressDialog
from PyQt5.QtGui import QIntValidator
from PyQt5.QtCore import QTimer
import re
import os
import ezdxf
import ezdxf.tools
import ezdxf.bbox
import ezdxf.units
import ezdxf.math
from coreldraw_checker import is_coreldraw_running
from functools import partial
import win32com.client
import os
import shutil
import threading
from clear_folder import another_function
class YourMainWindow5(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("多码混排")
layout = QVBoxLayout()
self.button1 = QPushButton("DXF文件路径")
self.button1.setFixedWidth(200)
self.button1.clicked.connect(self.showDxfFileDialog)
self.button2 = QPushButton("PLT文件路径")
self.button2.setFixedWidth(200)
self.button2.clicked.connect(self.showPltFileDialog)
self.initial_button1_text = self.button1.text()
self.initial_button2_text = self.button2.text()
panel1 = QGroupBox("文件路径")
panel1_layout = QVBoxLayout(panel1)
panel1_layout.setSpacing(10)
panel1_layout.setContentsMargins(10, 10, 10, 10)
panel1_layout.addWidget(self.button1)
panel1_layout.addWidget(self.button2)
layout.addWidget(panel1)
self.label5 = QLabel('单码片数')
self.lineEdit3 = QLineEdit()
self.lineEdit3.setValidator(QIntValidator())
self.lineEdit3.setFixedSize(120, 30)
layout.addWidget(self.label5)
layout.addWidget(self.lineEdit3)
self.scrollWidget = QWidget()
self.scrollWidgetLayout = QVBoxLayout(self.scrollWidget)
self.scrollArea = QScrollArea()
self.scrollArea.setWidget(self.scrollWidget)
self.scrollArea.setWidgetResizable(True)
layout.addWidget(self.scrollArea)
self.clearButton = QPushButton("清空信息")
self.clearButton.clicked.connect(self.clearScrollArea)
layout.addWidget(self.clearButton)
confirm_button = QPushButton("分割")
confirm_button.clicked.connect(self.updateScrollArea)
#confirm_button.clicked.connect(self.freezeAndParse) # 连接按钮点击事件
layout.addWidget(confirm_button)
central_widget = QWidget()
central_widget.setLayout(layout)
self.setCentralWidget(central_widget)
self.dxfLineEdits = {}
self.allowButtonActions = True # 标志变量,控制是否允许按钮行为
def run_coreldraw_macros(self):
try:
dogms = win32com.client.DispatchEx("CorelDRAW.Application.23")
macros_to_run = [
"RUN.OpenDXFFilesInFolder",
"RUN.RotateSelectionClockwise",
"RUN.DeleteUnnamedSublayers",
"RUN.StToFront",
"RUN.IterateSublayerNames",
]
for macro in macros_to_run:
dogms.GMSManager.RunMacro("RUNDXF", macro)
except Exception as e:
QMessageBox.warning(self, "警告", "缺少CDR模块请载入CDR模块", QMessageBox.Ok)
# print("缺少CDR模块请载入CDR模块")
def showPltFileDialog(self):
options = QFileDialog.Options()
file_path, _ = QFileDialog.getOpenFileName(self, "选择PLT文件", "", "PLT Files (*.plt);;All Files (*)",
options=options)
if file_path:
print("Selected PLT file:", file_path)
extracted_content = self.extract_content_from_plt_path(file_path)
print(extracted_content)
self.sizes = self.fill_sizes_from_extracted_content(extracted_content)
# 更新尺寸字典后,清空并填充滚动区域
self.clearScrollArea()
self.populateScrollArea()
self.initial_plt_path = file_path # 更新初始路径而不更新按钮文本
else:
print("No PLT file selected")
QMessageBox.warning(self, "警告", "没有选择文件夹。请重新选择文件夹。", QMessageBox.Ok)
pass
def showDxfFileDialog(self):
options = QFileDialog.Options()
file_path, _ = QFileDialog.getOpenFileName(self, "选择DXF文件", "", "DXF Files (*.dxf);;All Files (*)",
options=options)
if file_path:
print("Selected DXF file:", file_path)
self.initial_dxf_path = file_path # 更新初始路径而不更新按钮文本
else:
print("No DXF file selected")
QMessageBox.warning(self, "警告", "没有选择文件夹。请重新选择文件夹。", QMessageBox.Ok)
# 在此处添加提醒逻辑,例如使用 QMessageBox 提示用户没有选择文件
def extract_content_from_plt_path(self, plt_path):
match = re.search(r'\((.*?)\)', plt_path)
if match:
extracted_content = match.group(1)
return extracted_content
else:
return "No content in parentheses found"
def fill_sizes_from_extracted_content(self, extracted_content):
sizes = extracted_content.split("+")
size_dict = {}
for size in sizes:
size_dict[size] = ""
return size_dict
def process_dxf_file(self, file_path, extracted_content):
doc = ezdxf.readfile(file_path)
msp = doc.modelspace()
mspBox = ezdxf.bbox.extents(msp)
print("=====", os.path.basename(file_path))
print("左上角坐标:", mspBox.extmin)
print("画布宽:", mspBox.size[0], "画布高:", mspBox.size[1])
print()
for entity in msp.query():
if entity.dxftype() == "INSERT":
temp = []
rotation = None
block = doc.blocks[entity.dxf.name]
for e in block:
if e.dxftype() != "TEXT":
temp.append(e)
else:
rotation = e.dxf.rotation
if rotation is not None:
rotation %= 360
if 45 <= rotation < 135:
rotation = 90
elif 135 <= rotation < 225:
rotation = 180
elif 225 <= rotation < 315:
rotation = -90
else:
rotation = 0
print("=====", entity.dxf.name)
print("大小:", ezdxf.bbox.extents(temp).size)
print("文字角度:", rotation)
center = ezdxf.bbox.extents(temp).center
center = (center.x, mspBox.extmax.y - center.y) # 调整center y值
print("中心坐标:", center)
center = (center[1], mspBox.size[0] - center[0]) # 旋转后中心坐标
print("旋转后中心坐标:", center)
separator = "_" # 分隔符
entity.dxf.name += separator + str(rotation)
block.name += separator + str(rotation)
new_file_path = os.path.join(r"D:\marktemp", "{}.dxf".format(extracted_content))
doc.saveas(new_file_path)
def getSinglePieceCount(self):
return self.lineEdit3.text()
def recreate_folders(self):
# 定义文件夹路径
folder_paths = [r"D:\PSMARKtemp", r"D:\marktemp"]
# 删除文件夹及其内容
for folder_path in folder_paths:
if os.path.exists(folder_path):
shutil.rmtree(folder_path)
print(f"Deleted folder: {folder_path}")
# 重新创建文件夹
for folder_path in folder_paths:
os.makedirs(folder_path)
print(f"Recreated folder: {folder_path}")
def freezeAndParse(self):
self.parse_button.setEnabled(False) # 冻结按钮
QTimer.singleShot(10000, self.unfreezeButton) # 10秒后解冻按钮
def unfreezeButton(self):
self.parse_button.setEnabled(True) # 解冻按钮
def updateScrollArea(self):
another_function()
if not is_coreldraw_running():
QMessageBox.warning(self, "警告", "CorelDRAW未运行无法执行操作。")
return
plt_file_path = self.initial_plt_path
# 获取DXF文件路径
dxf_file_path = self.initial_dxf_path
extracted_content = self.extract_content_from_plt_path(plt_file_path)
if dxf_file_path:
# 去掉括号内内容后的PLT文件名作为DXF文件名
plt_filename = os.path.basename(plt_file_path)
# dxf_filename = re.sub(r'\(.*?\)', '', plt_filename)
self.process_dxf_file(dxf_file_path, extracted_content) # 调用解析函数并传入单码片数和新的DXF文件名
print("DXF文件解析完成")
else:
QMessageBox.warning(self, "警告", "没有选择DXF文件。请先选择一个DXF文件。", QMessageBox.Ok)
print()
self.run_coreldraw_macros()
single_code_pieces = int(self.getSinglePieceCount()) # 获取单码片数
print(single_code_pieces)
# 打印滚动区域中的输入框内容
code_quantities = {} # 创建一个新的字典用于存储数据
for label, line_edit in self.dxfLineEdits.items():
text = line_edit.text()
# print(f"Label: {label}, Text: {text}")
if text.isdigit():
value = int(text) # 尝试将文本转换为整数
else:
try:
value = float(text) # 尝试将文本转换为浮点数
except ValueError:
print(f"Invalid value for {label}: {text}")
continue # 转换失败,跳过当前循环迭代
code_quantities[label] = value # 存储转换后的数字到字典
# print(line_edit)
print(code_quantities)
keys_list = list(code_quantities.keys())
values_list = list(code_quantities.values())
# length = len(code_quantities)
# print(length) # 输出 3因为字典中有三对键值对
# 将text中的每个元素与code对应位置的元素相乘
result = [txt * single_code_pieces for txt in values_list]
# 使用zip函数将label和result对应组合
combined = zip(keys_list, result)
# 利用列表推导式生成结果数组
results2 = [lbl for lbl, txt in combined for _ in range(txt)]
# 打印结果数组
print(results2)
###############debug
corel_app = win32com.client.Dispatch("CorelDRAW.Application.23")
# 获取当前活动文档
active_document = corel_app.ActiveDocument
# 获取当前页面中所有图层的名称,排除特定名称的图层
layer_names = [layer.Name for layer in active_document.ActivePage.Layers
if layer.Name not in ["辅助线", "1", "0", "Defpoints"]]
p_numbers = [] # 初始化存储 P 数字的列表
for code, quantity in code_quantities.items():
for i in range(1, single_code_pieces + 1):
p_numbers.extend([f"P{i}"] * int(quantity))
print(p_numbers)
# 循环遍历不同的码
# p_numbers = [] # 初始化存储 P 数字的列表
#
# for code, quantity in code_quantities.items():
# for i in range(1, single_code_pieces + 1):
# # 根据码的数量分别生成对应数量的 P 数字,并添加到列表中
# p_numbers.extend([f"P{i}"] * quantity)
# print(p_numbers)
new_layer_names = []
index = 0
for old_name in layer_names:
parts = old_name.split("-") # 根据"-"分割字符串
if len(parts) > 1:
new_name = f"{p_numbers[index]}-{parts[1]}-{results2[index]}" # 使用数组中的 P 数字
new_layer_names.append(new_name)
index += 1
# 在新的图层名数组中遍历,对图层进行修改
modified_names = [] # 创建一个列表来存储修改后的名称
modified_names2 = []
for i, new_name in enumerate(new_layer_names):
active_document.ActivePage.Layers(layer_names[i]).Name = new_name
modified_names2.append(new_name)
modified_names.append(new_name)
print(f"Modified: {layer_names[i]} -> {new_name}")
dogms = win32com.client.DispatchEx("CorelDRAW.Application.23")
#
dogms.GMSManager.RunMacro("RUNDXF", "RUN.RUNPDF")
#
dogms.GMSManager.RunMacro("RUNDXF", "RUN.ActiveDocumentClose")
###############debug
# print(modified_names)
######### ######### ######### ######### #########这里是对多码的功能 这里是删除的功能
# def delete_layers_by_names(names_to_delete, active_document):
# corel_app = win32com.client.Dispatch("CorelDRAW.Application.23")
#
# # 获取当前活动文档
# active_document = corel_app.ActiveDocument
# for target_layer_name in names_to_delete:
# for layer in active_document.ActivePage.Layers:
# if layer.Name == target_layer_name:
# layer.Delete()
# break # 找到目标图层后中断循环
#
#
#
# modified_names_list = [] # 用于存储每次循环中的 modified_names 列表
# ######### ######### ######### ######### #########这里是对多码的功能 这里是导出PSD的功能 我这边要混排就对功能进行封禁
# Index = 0
# for code in code_quantities:
# quantity = code_quantities[code]
# total_pieces = quantity * single_code_pieces
#
# # 获取数组的前 total_pieces 个元素
# newmodified_names_filtered = modified_names[:total_pieces]
# # print(newmodified_names_filtered)
#
# result_array = [fruit for fruit in modified_names2 if fruit not in newmodified_names_filtered]
# result_array_length = len(result_array)
# print(result_array_length)
#
# delete_layers_by_names(result_array, active_document.ActivePage)
# # modified_names_list.append(modified_names) # 将 modified_names 添加到数组中
#
#
# dogms = win32com.client.DispatchEx("CorelDRAW.Application.23")
#
# dogms.GMSManager.RunMacro("RUNDXF", "RUN.ExportSelectionToPSD", Index)
#
# dogms.GMSManager.RunMacro("RUNDXF", "RUN.HOURUN", result_array_length)
#
# modified_names = modified_names[total_pieces:]
#
# Index += 1
#
#
# corel_app = win32com.client.Dispatch("CorelDRAW.Application.23")
#
# corel_app .GMSManager.RunMacro("RUNDXF", "RUN.ActiveDocumentClose")
#
# QMessageBox.warning(self, "提醒", "分割完成,请进行裁片套版操作。")
def updateLineEditsFromSizes(self):
for size_label, line_edit in self.dxfLineEdits.items():
self.sizes[size_label] = line_edit.text()
def populateScrollArea(self):
self.clearScrollArea()
for size_label, size_text in self.sizes.items():
size_layout = QHBoxLayout()
size_layout.addWidget(QLabel(size_label))
line_edit = QLineEdit()
line_edit.setValidator(QIntValidator())
line_edit.setFixedSize(100, 30)
line_edit.setText(size_text)
self.dxfLineEdits[size_label] = line_edit
size_layout.addWidget(line_edit)
self.scrollWidgetLayout.addLayout(size_layout)
def clearScrollArea(self):
for i in reversed(range(self.scrollWidgetLayout.count())):
item = self.scrollWidgetLayout.itemAt(i)
if isinstance(item, QHBoxLayout) or isinstance(item, QVBoxLayout):
while item.count():
widget = item.takeAt(0).widget()
if widget:
widget.deleteLater()
self.dxfLineEdits.clear() # 清空部件引用
if __name__ == '__main__':
app = QApplication(sys.argv)
mainWindow = YourMainWindow5()
mainWindow.show()
sys.exit(app.exec_())

View File

@@ -0,0 +1,226 @@
import json
import os
#import replicate
import requests
from PyQt5 import QtWidgets, QtGui, QtCore
# from dotenv import load_dotenv
import os
# load_dotenv() # 加载 .env 文件中的环境变量
url = 'http://43.139.183.222:5000'
class ImportPDFDialog6(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.initUI()
self.processed_image_path = None # 存储处理后的图片路径
def initUI(self):
self.setWindowTitle('图像处理参数输入')
# 布局
layout = QtWidgets.QVBoxLayout()
# 文件选择行
self.file_input = QtWidgets.QLineEdit(self)
# self.file_input.setPlaceholderText("选择文件路径 (如 1.jpg)")
layout.addWidget(self.file_input)
self.browse_button = QtWidgets.QPushButton('浏览', self)
self.browse_button.clicked.connect(self.browse_file)
layout.addWidget(self.browse_button)
self.prompt_input = QtWidgets.QLineEdit(self)
self.prompt_input.setPlaceholderText("提示词 ")
layout.addWidget(self.prompt_input)
self.creativity_input = QtWidgets.QDoubleSpinBox(self)
self.creativity_input.setRange(0, 1)
self.creativity_input.setSingleStep(0.01)
self.creativity_input.setValue(0.35) # 默认值
layout.addWidget(QtWidgets.QLabel("创造力 (0 - 3):"))
layout.addWidget(self.creativity_input)
self.resemblance_input = QtWidgets.QDoubleSpinBox(self)
self.resemblance_input.setRange(0, 3)
self.resemblance_input.setSingleStep(0.01)
self.resemblance_input.setValue(0.6) # 默认值
layout.addWidget(QtWidgets.QLabel("相似度 (0 - 3):"))
layout.addWidget(self.resemblance_input)
self.scale_factor_input = QtWidgets.QSpinBox(self)
self.scale_factor_input.setRange(2, 8)
self.scale_factor_input.setValue(2) # 默认值
layout.addWidget(QtWidgets.QLabel("放大倍数:"))
layout.addWidget(self.scale_factor_input)
self.submit_button = QtWidgets.QPushButton('提交', self)
self.submit_button.clicked.connect(self.submit)
layout.addWidget(self.submit_button)
# 合并图片显示和处理结果区域
self.output_area = QtWidgets.QVBoxLayout()
self.image_label = QtWidgets.QLabel(self)
# self.image_label.setText("加载的图片将显示在这里")
self.image_label.setAlignment(QtCore.Qt.AlignCenter)
self.output_area.addWidget(self.image_label)
self.result_display = QtWidgets.QTextEdit(self)
self.result_display.setReadOnly(True)
self.output_area.addWidget(QtWidgets.QLabel("处理结果:"))
self.output_area.addWidget(self.result_display)
layout.addLayout(self.output_area)
# 下载按钮
self.download_button = QtWidgets.QPushButton('下载', self)
self.download_button.clicked.connect(self.download_image)
self.download_button.setEnabled(False) # 初始不可用
layout.addWidget(self.download_button)
self.setLayout(layout)
def browse_file(self):
options = QtWidgets.QFileDialog.Options()
file_name, _ = QtWidgets.QFileDialog.getOpenFileName(self, "选择图像文件", "", "Image Files (*.png *.jpg *.jpeg *.bmp)", options=options)
if file_name:
self.file_input.setText(file_name)
self.display_image(file_name) # 显示选中的图片
def display_image(self, file_path):
pixmap = QtGui.QPixmap(file_path)
self.image_label.setPixmap(pixmap.scaled(300, 300, QtCore.Qt.KeepAspectRatio))
def upload_image(self, url, file_path, json_data):
imgurl = url + "/upload"
with open(file_path, 'rb') as file:
files = {'file': file}
data = {'data': json.dumps(json_data)} # 将 JSON 数据转换为字符串
response = requests.post(imgurl, files=files, data=data)
print(response.status_code)
response_json = response.json() # 先解析 JSON 响应
print(response_json) # 打印响应内容以检查其格式
# 确保响应是一个列表,并且至少有一个元素
if isinstance(response_json, list) and len(response_json) > 0:
self.processed_image_path = response_json[0] # 从列表中获取 URL
else:
# 处理不符合预期的情况
print("Unexpected response format:", response_json)
return
self.result_display.setPlainText(str(response_json)) # 显示处理结果
self.download_button.setEnabled(True) # 启用下载按钮
self.display_processed_image() # 显示处理后的图片
def submit(self):
try:
creativity = self.creativity_input.value()
file_path = self.file_input.text()
urlprompt = self.prompt_input.text() + " best quality, highres, <lora:more_details:0.5> <lora:SDXLrender_v2.0:1>"
prompt = urlprompt
resemblance = self.resemblance_input.value()
scale_factor = self.scale_factor_input.value()
if not os.path.exists(file_path):
raise ValueError("文件不存在,请选择有效的文件。")
input_data = {
"seed": 1337,
"prompt": prompt,
"dynamic": 6,
"handfix": "disabled",
"pattern": False,
"sharpen": 0,
"sd_model": "juggernaut_reborn.safetensors [338b85bc4f]",
"scheduler": "DPM++ 3M SDE Karras",
"creativity": creativity,
"lora_links": "",
"downscaling": False,
"resemblance": resemblance,
"scale_factor": scale_factor,
"tiling_width": 112,
"tiling_height": 144,
"output_format": "png",
"custom_sd_model": "",
"negative_prompt": "(worst quality, low quality, normal quality:2) JuggernautNegative-neg",
"num_inference_steps": 18,
"downscaling_resolution": 768
}
# 确保调用时只传递三个参数
self.upload_image(url, file_path, input_data)
except Exception as e:
QtWidgets.QMessageBox.critical(self, "错误", str(e))
def run(url):
newurl = url + "/data"
data = {'key': 'value'} # 你要发送的数据
response = requests.post(newurl, json=data)
print(response.status_code) # 打印状态码
print(response.json()) # 打印返回的 JSON 数据
def run2(url):
newurl = url + "/dataimg"
data = {'key': 'value'} # 你要发送的数据
response = requests.post(newurl, json=data)
print(response.status_code) # 打印状态码
print(response.json()) # 打印返回的 JSON 数据
# if __name__ == '__main__':
# upload_image(url, '1.jpg', {'key': 'value'})
def display_processed_image(self):
# 下载并显示处理后的图片
response = requests.get(self.processed_image_path)
if response.status_code == 200:
pixmap = QtGui.QPixmap()
pixmap.loadFromData(response.content)
self.image_label.setPixmap(pixmap.scaled(300, 300, QtCore.Qt.KeepAspectRatio))
def download_image(self):
if self.processed_image_path:
image_url = self.processed_image_path
file_name, _ = QtWidgets.QFileDialog.getSaveFileName(self, "保存处理后的图片", "", "Image Files (*.png *.jpg *.jpeg)")
if file_name:
try:
response = requests.get(image_url)
response.raise_for_status() # 检查请求是否成功
with open(file_name, 'wb') as f:
f.write(response.content)
QtWidgets.QMessageBox.information(self, "成功", "图片下载完成!")
except requests.exceptions.RequestException as e:
QtWidgets.QMessageBox.critical(self, "错误", f"下载失败:{e}")
except Exception as e:
QtWidgets.QMessageBox.critical(self, "错误", f"文件保存失败:{e}")
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
# 创建并显示登录界面
# login_dialog = LoginDialog()
# if login_dialog.exec_() == QtWidgets.QDialog.Accepted:
# 只有在登录成功后才执行以下代码
ex = ImportPDFDialog6()
ex.show()
sys.exit(app.exec_())

View File

@@ -0,0 +1,33 @@
import os
import threading
def clear_folder_contents(folder_paths):
def clear_folder(folder_path):
try:
for filename in os.listdir(folder_path):
file_path = os.path.join(folder_path, filename)
try:
if os.path.isfile(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
clear_folder(file_path)
os.rmdir(file_path)
except Exception as e:
print(f"无法删除 {file_path}: {e}")
except Exception as e:
print(f"无法列出文件夹内容 {folder_path}: {e}")
for folder_path in folder_paths:
thread = threading.Thread(target=clear_folder, args=(folder_path,))
thread.start()
def another_function():
folder1_to_clear = "D:\PSMarktemp"
#folder2_to_clear = "D:\MarkTemp\DXFmarktemp"
folder3_to_clear = "D:\markTemp"
folders_to_clear = [folder1_to_clear,folder3_to_clear]
clear_folder_contents(folders_to_clear)
# 在另一个函数中执行清空两个文件夹内容的操作
# folder_paths = [r"D:\MarkTemp\PSMarktemp", r"D:\MarkTemp\marktemp", r"D:\MarkTemp\marktemp"]

View File

@@ -0,0 +1,7 @@
import psutil
def is_coreldraw_running():
for process in psutil.process_iter(['pid', 'name']):
if process.info['name'] == "CorelDRW.exe":
return True
return False

View File

@@ -0,0 +1,31 @@
import os
import threading
def clear_folder_contents(folder_paths):
def clear_folder(folder_path):
try:
for filename in os.listdir(folder_path):
file_path = os.path.join(folder_path, filename)
try:
if os.path.isfile(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
clear_folder(file_path)
os.rmdir(file_path)
except Exception as e:
print(f"无法删除 {file_path}: {e}")
except Exception as e:
print(f"无法列出文件夹内容 {folder_path}: {e}")
for folder_path in folder_paths:
thread = threading.Thread(target=clear_folder, args=(folder_path,))
thread.start()
def another_function():
folder1_to_clear = "D:\PSMARKtemp"
folder2_to_clear = "D:\marktemp"
folders_to_clear = [folder1_to_clear, folder2_to_clear]
clear_folder_contents(folders_to_clear)
# 在另一个函数中执行清空两个文件夹内容的操作

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 119 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 114 KiB

View File

@@ -0,0 +1,51 @@
# -*- mode: python ; coding: utf-8 -*-
block_cipher = None
a = Analysis(
['main.py'],
pathex=[],
binaries=[],
datas=[],
hiddenimports=[],
hookspath=[],
hooksconfig={},
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher,
noarchive=False,
)
pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)
exe = EXE(
pyz,
a.scripts,
[],
exclude_binaries=True,
name='main',
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
console=False,
disable_windowed_traceback=False,
argv_emulation=False,
target_arch=None,
codesign_identity=None,
entitlements_file=None,
icon=['newapp.ico'],
)
coll = COLLECT(
exe,
a.binaries,
a.zipfiles,
a.datas,
strip=False,
upx=True,
upx_exclude=[],
name='main',
)

View File

@@ -0,0 +1,86 @@
from os.path import join, dirname, abspath
from qtpy.QtGui import QPalette, QColor
import qtpy, platform
QT_VERSION = tuple((int(v) for v in qtpy.QT_VERSION.split('.')))
PLATFORM = platform.system()
_STYLESHEET = 'black.css'
def _apply_base_theme(app):
""" Apply base theme to the application.
Args:
app (QApplication): QApplication instance.
"""
if QT_VERSION < (5, ):
app.setStyle('plastique')
else:
app.setStyle('Fusion')
with open(_STYLESHEET) as stylesheet:
app.setStyleSheet(stylesheet.read())
def dark(app):
""" Apply Dark Theme to the Qt application instance.
Args:
app (QApplication): QApplication instance.
"""
darkPalette = QPalette()
darkPalette.setColor(QPalette.WindowText, QColor(180, 180, 180))
darkPalette.setColor(QPalette.Button, QColor(53, 53, 53))
darkPalette.setColor(QPalette.Light, QColor(180, 180, 180))
darkPalette.setColor(QPalette.Midlight, QColor(90, 90, 90))
darkPalette.setColor(QPalette.Dark, QColor(35, 35, 35))
darkPalette.setColor(QPalette.Text, QColor(180, 180, 180))
darkPalette.setColor(QPalette.BrightText, QColor(180, 180, 180))
darkPalette.setColor(QPalette.ButtonText, QColor(180, 180, 180))
darkPalette.setColor(QPalette.Base, QColor(42, 42, 42))
darkPalette.setColor(QPalette.Window, QColor(53, 53, 53))
darkPalette.setColor(QPalette.Shadow, QColor(20, 20, 20))
darkPalette.setColor(QPalette.Highlight, QColor(42, 130, 218))
darkPalette.setColor(QPalette.HighlightedText, QColor(180, 180, 180))
darkPalette.setColor(QPalette.Link, QColor(56, 252, 196))
darkPalette.setColor(QPalette.AlternateBase, QColor(66, 66, 66))
darkPalette.setColor(QPalette.ToolTipBase, QColor(53, 53, 53))
darkPalette.setColor(QPalette.ToolTipText, QColor(180, 180, 180))
darkPalette.setColor(QPalette.Disabled, QPalette.WindowText, QColor(127, 127, 127))
darkPalette.setColor(QPalette.Disabled, QPalette.Text, QColor(127, 127, 127))
darkPalette.setColor(QPalette.Disabled, QPalette.ButtonText, QColor(127, 127, 127))
darkPalette.setColor(QPalette.Disabled, QPalette.Highlight, QColor(80, 80, 80))
darkPalette.setColor(QPalette.Disabled, QPalette.HighlightedText, QColor(127, 127, 127))
app.setPalette(darkPalette)
_apply_base_theme(app)
def light(app):
""" Apply Light Theme to the Qt application instance.
Args:
app (QApplication): QApplication instance.
"""
lightPalette = QPalette()
lightPalette.setColor(QPalette.WindowText, QColor(0, 0, 0))
lightPalette.setColor(QPalette.Button, QColor(240, 240, 240))
lightPalette.setColor(QPalette.Light, QColor(180, 180, 180))
lightPalette.setColor(QPalette.Midlight, QColor(200, 200, 200))
lightPalette.setColor(QPalette.Dark, QColor(225, 225, 225))
lightPalette.setColor(QPalette.Text, QColor(0, 0, 0))
lightPalette.setColor(QPalette.BrightText, QColor(0, 0, 0))
lightPalette.setColor(QPalette.ButtonText, QColor(0, 0, 0))
lightPalette.setColor(QPalette.Base, QColor(237, 237, 237))
lightPalette.setColor(QPalette.Window, QColor(240, 240, 240))
lightPalette.setColor(QPalette.Shadow, QColor(20, 20, 20))
lightPalette.setColor(QPalette.Highlight, QColor(76, 163, 224))
lightPalette.setColor(QPalette.HighlightedText, QColor(0, 0, 0))
lightPalette.setColor(QPalette.Link, QColor(0, 162, 232))
lightPalette.setColor(QPalette.AlternateBase, QColor(225, 225, 225))
lightPalette.setColor(QPalette.ToolTipBase, QColor(240, 240, 240))
lightPalette.setColor(QPalette.ToolTipText, QColor(0, 0, 0))
lightPalette.setColor(QPalette.Disabled, QPalette.WindowText, QColor(115, 115, 115))
lightPalette.setColor(QPalette.Disabled, QPalette.Text, QColor(115, 115, 115))
lightPalette.setColor(QPalette.Disabled, QPalette.ButtonText, QColor(115, 115, 115))
lightPalette.setColor(QPalette.Disabled, QPalette.Highlight, QColor(190, 190, 190))
lightPalette.setColor(QPalette.Disabled, QPalette.HighlightedText, QColor(115, 115, 115))
app.setPalette(lightPalette)
_apply_base_theme(app)

View File

@@ -0,0 +1,159 @@
from os.path import join, dirname, abspath
from qtpy.QtCore import Qt, QMetaObject, Signal, Slot, QEvent
from qtpy.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QToolButton, QLabel, QSizePolicy
from PyQt5.QtGui import QIcon, QPixmap
import qtpy, platform
QT_VERSION = tuple((int(v) for v in qtpy.QT_VERSION.split('.')))
PLATFORM = platform.system()
_FL_STYLESHEET = 'frameless.qss'
class WindowDragger(QWidget):
'''Window dragger.
Args:
window (QWidget): Associated window.
parent (QWidget, optional): Parent widget.
'''
doubleClicked = Signal()
def __init__(self, window, parent=None):
QWidget.__init__(self, parent)
self._window = window
self._mousePressed = False
def mousePressEvent(self, event):
self._mousePressed = True
self._mousePos = event.globalPos()
self._windowPos = self._window.pos()
def mouseMoveEvent(self, event):
if self._mousePressed:
self._window.move(self._windowPos + (event.globalPos() - self._mousePos))
def mouseReleaseEvent(self, event):
self._mousePressed = False
def mouseDoubleClickEvent(self, event):
self.doubleClicked.emit()
class ModernWindow(QWidget):
'''
Modern window.
Args:
w (QWidget): Main widget.
parent (QWidget, optional): Parent widget.
'''
def __init__(self, w, parent=None):
QWidget.__init__(self, parent)
self._w = w
self.setupUi()
contentLayout = QHBoxLayout()
contentLayout.setContentsMargins(0, 0, 0, 0)
contentLayout.addWidget(w)
self.windowContent.setLayout(contentLayout)
self.setWindowTitle(w.windowTitle())
self.setGeometry(w.geometry())
self._w.setAttribute(Qt.WA_DeleteOnClose, True)
self._w.destroyed.connect(self._ModernWindow__child_was_closed)
def setupUi(self):
self.vboxWindow = QVBoxLayout(self)
self.vboxWindow.setContentsMargins(0, 0, 0, 0)
self.windowFrame = QWidget(self)
self.windowFrame.setObjectName('windowFrame')
self.vboxFrame = QVBoxLayout(self.windowFrame)
self.vboxFrame.setContentsMargins(0, 0, 0, 0)
self.titleBar = WindowDragger(self, self.windowFrame)
self.titleBar.setObjectName('titleBar')
self.titleBar.setSizePolicy(QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed))
self.hboxTitle = QHBoxLayout(self.titleBar)
self.hboxTitle.setContentsMargins(0, 0, 0, 0)
self.hboxTitle.setSpacing(0)
titleIcon = QPixmap('./ui/icon.png')
Icon = QLabel()
Icon.setPixmap(titleIcon.scaled(30, 30))
self.icon = Icon
self.icon.setAlignment(Qt.AlignLeft)
self.lblTitle = QLabel('Title')
self.lblTitle.setObjectName('lblTitle')
self.lblTitle.setAlignment(Qt.AlignVCenter)
spButtons = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
self.btnMinimize = QToolButton(self.titleBar)
self.btnMinimize.setObjectName('btnMinimize')
self.btnMinimize.setSizePolicy(spButtons)
self.btnRestore = QToolButton(self.titleBar)
self.btnRestore.setObjectName('btnRestore')
self.btnRestore.setSizePolicy(spButtons)
self.btnRestore.setVisible(False)
self.btnMaximize = QToolButton(self.titleBar)
self.btnMaximize.setObjectName('btnMaximize')
self.btnMaximize.setSizePolicy(spButtons)
self.btnClose = QToolButton(self.titleBar)
self.btnClose.setObjectName('btnClose')
self.btnClose.setSizePolicy(spButtons)
self.vboxFrame.addWidget(self.titleBar)
self.windowContent = QWidget(self.windowFrame)
self.vboxFrame.addWidget(self.windowContent)
self.vboxWindow.addWidget(self.windowFrame)
PLATFORM = '1Darwin'
if PLATFORM == 'Darwin':
self.hboxTitle.addWidget(self.btnClose)
self.hboxTitle.addWidget(self.btnMinimize)
self.hboxTitle.addWidget(self.btnRestore)
self.hboxTitle.addWidget(self.btnMaximize)
self.hboxTitle.addWidget(self.lblTitle)
else:
self.hboxTitle.addWidget(self.icon)
self.hboxTitle.addWidget(self.lblTitle)
self.hboxTitle.addWidget(self.btnMinimize)
self.hboxTitle.addWidget(self.btnRestore)
self.hboxTitle.addWidget(self.btnMaximize)
self.hboxTitle.addWidget(self.btnClose)
self.setWindowFlags(Qt.Window | Qt.FramelessWindowHint | Qt.WindowSystemMenuHint)
with open(_FL_STYLESHEET) as (stylesheet):
self.setStyleSheet(stylesheet.read())
QMetaObject.connectSlotsByName(self)
def __child_was_closed(self):
self._w = None
self.close()
def closeEvent(self, event):
if not self._w:
event.accept()
else:
self._w.close()
event.setAccepted(self._w.isHidden())
def setWindowTitle(self, title):
super(ModernWindow, self).setWindowTitle(title)
self.lblTitle.setText(title)
@Slot()
def on_btnMinimize_clicked(self):
self.setWindowState(Qt.WindowMinimized)
@Slot()
def on_btnRestore_clicked(self):
self.btnRestore.setVisible(False)
self.btnMaximize.setVisible(True)
self.setWindowState(Qt.WindowNoState)
@Slot()
def on_btnMaximize_clicked(self):
self.btnRestore.setVisible(True)
self.btnMaximize.setVisible(False)
self.setWindowState(Qt.WindowMaximized)
@Slot()
def on_btnClose_clicked(self):
self.close()
@Slot()
def on_titleBar_doubleClicked(self):
if self.btnMaximize.isVisible():
self.on_btnMaximize_clicked()
else:
self.on_btnRestore_clicked()

View File

@@ -0,0 +1,351 @@
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QTabWidget, QPushButton, QLabel, QVBoxLayout, QWidget, QHBoxLayout, QFrame, QMessageBox
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import Qt
from Tab1 import ImportPDFDialog
from Tab2 import YourMainWindow
from Tab3 import ImportPDFDialog2
from Tab6 import ImportPDFDialog6
from Tab4 import ImportPDFDialog4
from test5 import YourMainWindow9
import qdarktheme
import sys
import subprocess
import re
import hashlib
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QPushButton, QGroupBox, \
QSpacerItem, QSizePolicy, QMessageBox
import pymysql
import piece_decorative
import configparser
def exception_hook(exctype, value, traceback):
# Handle the uncaught exception
# 处理未捕获的异常
QMessageBox.warning(None, "错误", f"发生了未知的异常:{value}")
# class LoginDialog(QWidget):
# def __init__(self):
# super().__init__()
# self.setWindowTitle("PSMARK登录界面")
# self.setWindowIcon(QIcon("icons/newapp.ico")) # 设置窗口小图标,替换为您的图标文件路径
#
# self.resize(300, 200)
#
# 主布局 = QVBoxLayout()
#
# group1 = QGroupBox("登录验证")
# group1_layout = QVBoxLayout()
#
# group2 = QHBoxLayout()
# label1 = QLabel("用户名")
# self.edit1 = QLineEdit()
# self.edit1.setFixedWidth(200)
# spacer1 = QSpacerItem(40, 10, QSizePolicy.Expanding, QSizePolicy.Minimum)
# group2.addWidget(label1)
# group2.addItem(spacer1)
# group2.addWidget(self.edit1)
#
# group3 = QHBoxLayout()
# label2 = QLabel("密码")
# self.edit2 = QLineEdit()
# self.edit2.setFixedWidth(200)
# self.edit2.setEchoMode(QLineEdit.Password) # 设置密码输入框为密文
# spacer2 = QSpacerItem(40, 10, QSizePolicy.Expanding, QSizePolicy.Minimum)
# group3.addWidget(label2)
# group3.addItem(spacer2)
# group3.addWidget(self.edit2)
#
#
#
# group4 = QHBoxLayout()
# button1 = QPushButton("登录")
# button2 = QPushButton("注册")
# group4.addWidget(button1)
# group4.addWidget(button2)
#
# group1_layout.addLayout(group2)
# group1_layout.addLayout(group3)
# group1_layout.addLayout(group4)
# group1.setLayout(group1_layout)
#
# 主布局.addWidget(group1)
#
# group5 = QHBoxLayout()
# label3 = QLabel("机器码")
# self.edit3 = QLineEdit()
# self.edit3.setFixedWidth(200)
#
# # 获取主板序列号并提取数字部分
# try:
# result = subprocess.run(['wmic', 'baseboard', 'get', 'serialnumber'], stdout=subprocess.PIPE,
# stderr=subprocess.PIPE, text=True)
# motherboard_serial = result.stdout.strip()
#
# # 使用正则表达式提取数字
# motherboard_serial = re.sub(r'\D', '', motherboard_serial)
#
# # 使用SHA-256加密特征码
# feature_code = hashlib.sha256(motherboard_serial.encode()).hexdigest()
#
# # 去掉特征码中的英文字符
# feature_code = re.sub(r'[a-zA-Z]', '', feature_code)
# except Exception as e:
# feature_code = "Error: " + str(e)
#
# self.edit3.setText(feature_code) # 将加密后的特征码设置为 "特征码" 输入框的文本
# self.rem_user()
#
# spacer3 = QSpacerItem(10, 10, QSizePolicy.Fixed, QSizePolicy.Minimum)
# group5.addWidget(label3)
# group5.addItem(spacer3)
# group5.addWidget(self.edit3)
#
# 主布局.addLayout(group5)
#
# self.setLayout(主布局)
#
# # 链接登录的点击事件
# button1.clicked.connect(self.slot_login)
# # 连接注册按钮的点击事件
# button2.clicked.connect(self.show_warning_message)
#
# #记住密码
# def rem_user(self):
#
# piece_decorative.config = configparser.ConfigParser()
# piece_decorative.config.read('config.ini', encoding='utf-8')
# piece_decorative.PSname = piece_decorative.config.get('程序配置', 'PSname')
# self.window = MainWindow()
# self.window.show()
# self.close()
# return
#
# code = self.edit3.text()
# # 执行SQL语句从user数据表中查询字段值
# cur.execute(f"SELECT username,password,code FROM {User}")
# # 将数据库查询的结果保存在result中
# result = cur.fetchall()
# code_list = [it[2] for it in result] # 从数据库查询的result中遍历查询元组中第3个元素code
# if code in code_list:
# user_name = result[code_list.index(code)][0]
# user_password = result[code_list.index(code)][1]
# self.edit1.setText(user_name)
# self.edit2.setText(user_password)
# else:
# pass
#
# def slot_login(self):
# user_name = self.edit1.text()
# user_password = self.edit2.text()
# code = self.edit3.text()
# # print(user_name,user_password)
# # 执行SQL语句从user数据表中查询code和time字段值
# cur.execute(f"SELECT username,password,code FROM {User}")
# # 将数据库查询的结果保存在result中
# result = cur.fetchall()
# name_list = [it[0] for it in result] # 从数据库查询的result中遍历查询元组中第一个元素name
# # 判断用户名或密码不能为空
# if not (user_name and user_password):
# QMessageBox.critical(self, "错误", "用户名或密码不能为空!")
# # 判断用户名和密码是否匹配
# elif user_name in name_list:
# if user_password == result[name_list.index(user_name)][1]:
# if code == result[name_list.index(user_name)][2]:
# piece_decorative.config = configparser.ConfigParser()
# piece_decorative.config.read('config.ini', encoding='utf-8')
# piece_decorative.PSname = piece_decorative.config.get('程序配置', 'PSname')
# self.window = MainWindow()
# self.window.show()
# self.close()
# else:
# QMessageBox.critical(self, "错误", "机器码不匹配!")
# # QMessageBox.information(self, "欢迎您", "登录成功!\n在此添加新界面")
# else:
# QMessageBox.critical(self, "错误", "密码输入错误!")
# # 账号不在数据库中,则弹出是否注册的框
# else:
# QMessageBox.critical(self, "错误", "该账号不存在,请注册!")
#
# def show_warning_message(self):
# # 弹出警告消息框
# QMessageBox.critical(self, "错误", "请联系管理员 17520145271")
# # warning_message = QMessageBox()
# # warning_message.setIcon(QMessageBox.Warning)
# # warning_message.setWindowTitle("警告")
# # warning_message.setText("请联系管理员 17520145271")
# # warning_message.exec_()
#################################自定义tab标签#################################
from PyQt5 import QtGui, QtCore, QtWidgets
class MyTabBar(QtWidgets.QTabBar):
def paintEvent(self, event):
painter = QtWidgets.QStylePainter(self)
option = QtWidgets.QStyleOptionTab()
for index in range(self.count()):
self.initStyleOption(option, index)
painter.drawControl(QtWidgets.QStyle.CE_TabBarTabShape, option)
painter.drawText(
self.tabRect(index),
QtCore.Qt.AlignCenter | QtCore.Qt.TextDontClip,
"\n".join(self.tabText(index)))
def tabSizeHint(self, index):
#size = QtWidgets.QTabBar.tabSizeHint(self, index)
width = max([QtWidgets.QTabBar.fontMetrics(self).width(text) for text in self.tabText(index)])
height = len(self.tabText(index)) * QtWidgets.QTabBar.fontMetrics(self).lineSpacing()
return QtCore.QSize(width + 12, height + 12)
class TabWidget(QtWidgets.QTabWidget):
def __init__(self, parent=None):
QtWidgets.QTabWidget.__init__(self, parent)
self.setTabBar(MyTabBar())
#################################自定义tab标签#################################
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("PS Mark")
self.setWindowIcon(QIcon("icons/newapp.ico")) # 设置窗口小图标,替换为您的图标文件路径
main_widget = QWidget()
self.setCentralWidget(main_widget)
main_layout = QVBoxLayout()
main_widget.setLayout(main_layout)
tab_widget = TabWidget()
tab_widget.setTabPosition(TabWidget.West)
#tab_widget.tabBar().setStyle(TabBarStyle(Qt.Vertical))
main_layout.addWidget(tab_widget)
tab2 = YourMainWindow()
tab_widget.addTab(tab2, "纸样分割")
tab1 = ImportPDFDialog()
tab_widget.addTab(tab1, "裁片套版")
#
#
tab3 = ImportPDFDialog2()
tab_widget.addTab(tab3, "快速换图")
# tab6 = ImportPDFDialog6()
# tab_widget.addTab(tab6, "ai重绘")
#
# tab3 = YourMainWindow9()
# tab_widget.addTab(tab3, "快速换图")
# tab4 = ImportPDFDialog4()
# tab_widget.addTab(tab4, "版本介绍")
#
# separator = QFrame()
# separator.setFrameShape(QFrame.HLine)
# separator.setFrameShadow(QFrame.Sunken)
# main_layout.addWidget(separator)
#custom_label = QLabel("尊敬的公司内部体验版用户(1.8.5),欢迎使用!!!")
#############8-12号修复了宽高缩放跟比例缩放超过10个裁片就会定位不准的bug
#############8-12号将缩水值跟前缀添加改为了前置条件
#############8-24号新增Tab2界面 将DXF解析与CDR结合在一起 可以实现分段排版
# main_layout.addWidget(custom_label)
self.setLayout(main_layout)
# # self.setWindowTitle("分割线和自定义文字示例")
# settings_button = QPushButton(QIcon("icons/转换.png"), "")
# settings_button.setObjectName("settingsButton") # 设置对象名称以供样式表选择
# settings_button.setStyleSheet("border: none;") # 设置按钮无边框
# main_layout.addWidget(settings_button, alignment=Qt.AlignLeft)
# 设置窗口始终置顶
self.setWindowFlags(Qt.WindowStaysOnTopHint)
self.width_ratio = 0.3
self.height_ratio = 1
self.initial_width = self.width()
self.initial_height = self.height()
# def resizeEvent(self, event):
# super().resizeEvent(event)
#
# # 获取当前窗口的宽度和高度
# current_width = self.width()
# current_height = self.height()
#
# # 判断当前窗口是否超过了初始大小
# if current_width > self.initial_width or current_height > self.initial_height:
# # 允许窗口继续拉伸,不设置最小宽度和最小高度
# pass
# else:
# # 重新设置最小宽度和最小高度为初始大小
# self.setMinimumWidth(self.initial_width)
# self.setMinimumHeight(self.initial_height)
def resizeEvent(self, event):
super().resizeEvent(event)
# 获取当前窗口的宽度和高度
current_width = self.width()
current_height = self.height()
# 如果是第一次调整大小,更新初始大小
if not hasattr(self, 'initial_size_set') or not self.initial_size_set:
self.initial_width = current_width
self.initial_height = current_height
self.initial_size_set = True # 标记初始大小已被设置
# 判断当前窗口是否超过了初始大小
if current_width > self.initial_width or current_height > self.initial_height:
# 允许窗口继续拉伸,不设置最小宽度和最小高度
pass
else:
# 重新设置最小宽度和最小高度为初始大小
self.setMinimumWidth(self.initial_width)
self.setMinimumHeight(self.initial_height)
if __name__ == '__main__':
host = "rm-bp1s36ps814qp23b7uo.mysql.rds.aliyuncs.com"
user = "zw1847930177"
password = "Zuowei1216"
database = "program"
charset = "utf8"
port = 3306
db = pymysql.connect(host=host, user=user, password=password, database=database, charset=charset, port=port)
cur = db.cursor()
user_creat ="""
CREATE TABLE IF NOT EXISTS User(
`id` INT auto_increment PRIMARY KEY,
`username` varchar(255) DEFAULT '',
`password` varchar(255) DEFAULT '',
`code` varchar(255) DEFAULT ''
) ENGINE=innodb DEFAULT CHARSET=utf8;
"""
cur.execute(user_creat)
cur = db.cursor()
User = 'User'
app3 = QApplication(sys.argv)
sys.excepthook = exception_hook # 设置全局异常处理
qdarktheme.setup_theme(
custom_colors={
"[dark]": {
"background": "#4d4d4d",
"foreground": "#ffffff",
"primary": "#ffffff",
"border": "#717070",
}
}
)
# login_dialog = LoginDialog()
# login_dialog.show()
window = MainWindow()
window.show()
sys.exit(app3.exec_())

View File

@@ -0,0 +1,51 @@
# -*- mode: python ; coding: utf-8 -*-
block_cipher = None
a = Analysis(
['newMark.py'],
pathex=[],
binaries=[],
datas=[],
hiddenimports=[],
hookspath=[],
hooksconfig={},
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher,
noarchive=False,
)
pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)
exe = EXE(
pyz,
a.scripts,
[],
exclude_binaries=True,
name='newMark',
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
console=False,
disable_windowed_traceback=False,
argv_emulation=False,
target_arch=None,
codesign_identity=None,
entitlements_file=None,
icon=['newapp.ico'],
)
coll = COLLECT(
exe,
a.binaries,
a.zipfiles,
a.datas,
strip=False,
upx=True,
upx_exclude=[],
name='newMark',
)

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

Some files were not shown because too many files have changed in this diff Show More