废弃老版图片压缩工具,使用工具集插件中的代替

This commit is contained in:
dgflash
2026-02-22 22:47:27 +08:00
parent fca918c47c
commit 2da486bd77
8 changed files with 7 additions and 373 deletions

View File

@@ -183,9 +183,7 @@ export abstract class CCEntity extends ecs.Entity {
layer.onClose = () => {
try {
const view = node.getComponent(ctor) as unknown as ecs.Comp;
if (view) {
this.remove(ctor as unknown as CompType<ecs.IComp>);
}
if (view) this.remove(ctor as unknown as CompType<ecs.IComp>);
}
catch (error) {
console.error(`移除界面组件失败: ${key}`, error);

20
dist/assets-menu.js vendored
View File

@@ -1,27 +1,9 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.onAssetMenu = void 0;
const tinypng_1 = require("./tinypng");
/** 资源栏右键菜单 */
function onAssetMenu(assetInfo) {
return [
{
label: 'i18n:oops-framework.name',
submenu: [
{
label: `i18n:oops-framework.tools_asset_menu`,
submenu: [
{
label: `i18n:oops-framework.tools_compress`,
click() {
(0, tinypng_1.compress)(assetInfo.file);
},
}
]
}
],
},
];
return [];
}
exports.onAssetMenu = onAssetMenu;
;

160
dist/tinypng.js vendored
View File

@@ -1,160 +0,0 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.compress = void 0;
const fs_1 = __importDefault(require("fs"));
const https_1 = __importDefault(require("https"));
const path_1 = __importDefault(require("path"));
const url_1 = __importDefault(require("url"));
const exts = ['.png', '.jpg', '.jpeg'];
const max = 5200000;
const options = {
method: 'POST',
hostname: 'tinypng.com',
path: '/backend/opt/shrink',
headers: {
rejectUnauthorized: 'false',
'Postman-Token': Date.now(),
'Cache-Control': 'no-cache',
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'
}
};
function compress(filePath) {
if (!fs_1.default.existsSync(filePath)) {
console.log(`路径不存在:${filePath}`);
return;
}
const fileName = path_1.default.basename(filePath);
if (!fs_1.default.statSync(filePath).isDirectory()) {
if (exts.includes(path_1.default.extname(filePath))) {
console.log(`[${fileName}] 压缩中...`);
fileTinyUpload(filePath)
.then(data => {
console.log(`[1/1] [${fileName}] 压缩成功,原始: ${toSize(data.input.size)},压缩: ${toSize(data.output.size)},压缩比: ${toPercent(data.output.ratio)}`);
})
.catch(err => {
console.log(`[1/1] [${fileName}] 压缩失败!报错:${err}`);
});
}
else {
console.log(`[${fileName}] 压缩失败!报错:只支持 png、jpg 与 jpeg 格式`);
}
}
else {
let totalCount = 0;
let processedCount = 0;
fileEach(filePath, (filePathInDir) => {
totalCount++;
const relativePath = path_1.default.relative(filePath, filePathInDir);
fileTinyUpload(filePathInDir)
.then(data => {
console.log(`[${++processedCount}/${totalCount}] [${relativePath}] 压缩成功,原始: ${toSize(data.input.size)},压缩: ${toSize(data.output.size)},压缩比: ${toPercent(data.output.ratio)}`);
})
.catch(err => {
console.log(`[${++processedCount}/${totalCount}] [${relativePath}] 压缩失败!报错:${err}`);
});
});
}
}
exports.compress = compress;
function getRandomIP() {
return Array.from(Array(4)).map(() => Math.floor(255 * Math.random())).join('.');
}
function fileEach(dir, callback) {
fs_1.default.readdir(dir, (err, files) => {
if (err) {
console.error(err);
return;
}
files.forEach((file) => {
const filePath = path_1.default.join(dir, file);
fs_1.default.stat(filePath, (statErr, stats) => {
if (statErr) {
console.error(statErr);
return;
}
if (stats.isDirectory()) {
fileEach(filePath, callback);
}
else {
if (stats.size <= max && stats.isFile() && exts.includes(path_1.default.extname(file))) {
callback(filePath);
}
}
});
});
});
}
function fileUpload(filePath) {
return new Promise((resolve, reject) => {
options.headers['X-Forwarded-For'] = getRandomIP();
const req = https_1.default.request(options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
try {
const result = JSON.parse(data);
if (result.error) {
reject(result.message);
}
else {
resolve(result);
}
}
catch (parseErr) {
reject(parseErr);
}
});
});
req.write(fs_1.default.readFileSync(filePath), 'binary');
req.on('error', err => {
reject(err);
});
req.end();
});
}
function fileUpdate(filePath, data) {
return new Promise((resolve, reject) => {
const urlObj = new url_1.default.URL(data.output.url);
const req = https_1.default.request(urlObj, (res) => {
let body = '';
res.setEncoding('binary');
res.on('data', (chunk) => {
body += chunk;
});
res.on('end', () => {
fs_1.default.writeFile(filePath, body, 'binary', (err) => {
if (err) {
reject(err);
}
else {
resolve(data);
}
});
});
});
req.on('error', (err) => {
reject(err);
});
req.end();
});
}
function fileTinyUpload(filePath) {
return fileUpload(filePath).then(data => fileUpdate(filePath, data));
}
function toSize(size) {
if (size < 1024)
return size + 'B';
else if (size < 1048576)
return (size / 1024).toFixed(2) + 'KB';
else
return (size / 1024 / 1024).toFixed(2) + 'MB';
}
function toPercent(ratio) {
return (100 * ratio).toFixed(2) + '%';
}

View File

@@ -19,8 +19,6 @@ module.exports = {
createView: "Create ECS view layer script",
createViewMvvm: "Create ECS view layer script - MVVM",
tools: "Framework Tools",
tools_asset_menu: "Tools",
tools_compress: "Image Compression",
tools_animator_editor: "Animation State Machine Editor",
panel_create_file: "Create Framework Template",
};
};

View File

@@ -19,8 +19,6 @@ module.exports = {
createView: "创建 ECS 视图层脚本",
createViewMvvm: "创建 ECS 视图层脚本 - MVVM",
tools: "框架工具",
tools_asset_menu: "工具",
tools_compress: "图片压缩",
tools_animator_editor: "动画状态机编辑器",
panel_create_file: "创建框架模板"
};
};

View File

@@ -28,12 +28,7 @@
"readonly": false
}
},
"assets": {
"menu": {
"methods": "./dist/assets-menu.js",
"assetMenu": "onAssetMenu"
}
},
"menu": [
{
"path": "i18n:oops-framework.name/i18n:oops-framework.tools",

View File

@@ -1,24 +1,6 @@
import { AssetInfo } from "../@types/packages/asset-db/@types/public";
import { compress } from "./tinypng";
/** 资源栏右键菜单 */
export function onAssetMenu(assetInfo: AssetInfo) {
return [
{
label: 'i18n:oops-framework.name',
submenu: [
{
label: `i18n:oops-framework.tools_asset_menu`,
submenu: [
{
label: `i18n:oops-framework.tools_compress`,
click() {
compress(assetInfo.file);
},
}
]
}
],
},
];
};
return [];
};

View File

@@ -1,159 +0,0 @@
import fs from 'fs';
import https from 'https';
import path from 'path';
import url from 'url';
const exts = ['.png', '.jpg', '.jpeg'];
const max = 5200000;
const options: any = {
method: 'POST',
hostname: 'tinypng.com',
path: '/backend/opt/shrink',
headers: {
rejectUnauthorized: 'false',
'Postman-Token': Date.now(),
'Cache-Control': 'no-cache',
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'
}
};
export function compress(filePath: string): void {
if (!fs.existsSync(filePath)) {
console.log(`路径不存在:${filePath}`);
return;
}
const fileName = path.basename(filePath);
if (!fs.statSync(filePath).isDirectory()) {
if (exts.includes(path.extname(filePath))) {
console.log(`[${fileName}] 压缩中...`);
fileTinyUpload(filePath)
.then(data => {
console.log(`[1/1] [${fileName}] 压缩成功,原始: ${toSize(data.input.size)},压缩: ${toSize(data.output.size)},压缩比: ${toPercent(data.output.ratio)}`);
})
.catch(err => {
console.log(`[1/1] [${fileName}] 压缩失败!报错:${err}`);
});
}
else {
console.log(`[${fileName}] 压缩失败!报错:只支持 png、jpg 与 jpeg 格式`);
}
}
else {
let totalCount = 0;
let processedCount = 0;
fileEach(filePath, (filePathInDir) => {
totalCount++;
const relativePath = path.relative(filePath, filePathInDir);
fileTinyUpload(filePathInDir)
.then(data => {
console.log(`[${++processedCount}/${totalCount}] [${relativePath}] 压缩成功,原始: ${toSize(data.input.size)},压缩: ${toSize(data.output.size)},压缩比: ${toPercent(data.output.ratio)}`);
})
.catch(err => {
console.log(`[${++processedCount}/${totalCount}] [${relativePath}] 压缩失败!报错:${err}`);
});
});
}
}
function getRandomIP(): string {
return Array.from(Array(4)).map(() => Math.floor(255 * Math.random())).join('.');
}
function fileEach(dir: string, callback: (filePath: string) => void): void {
fs.readdir(dir, (err: any, files: any[]) => {
if (err) {
console.error(err);
return;
}
files.forEach((file: any) => {
const filePath = path.join(dir, file);
fs.stat(filePath, (statErr: any, stats: { isDirectory: () => any; size: number; isFile: () => any; }) => {
if (statErr) {
console.error(statErr);
return;
}
if (stats.isDirectory()) {
fileEach(filePath, callback);
}
else {
if (stats.size <= max && stats.isFile() && exts.includes(path.extname(file))) {
callback(filePath);
}
}
});
});
});
}
function fileUpload(filePath: string): Promise<any> {
return new Promise((resolve, reject) => {
options.headers['X-Forwarded-For'] = getRandomIP();
const req = https.request(options, (res: any) => {
let data = '';
res.on('data', (chunk: string) => {
data += chunk;
});
res.on('end', () => {
try {
const result = JSON.parse(data);
if (result.error) {
reject(result.message);
} else {
resolve(result);
}
} catch (parseErr) {
reject(parseErr);
}
});
});
req.write(fs.readFileSync(filePath), 'binary');
req.on('error', err => {
reject(err);
});
req.end();
});
}
function fileUpdate(filePath: string, data: any): Promise<any> {
return new Promise((resolve, reject) => {
const urlObj = new url.URL(data.output.url);
const req = https.request(urlObj, (res: any) => {
let body = '';
res.setEncoding('binary');
res.on('data', (chunk: string) => {
body += chunk;
});
res.on('end', () => {
fs.writeFile(filePath, body, 'binary', (err: any) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
});
req.on('error', (err: any) => {
reject(err);
});
req.end();
});
}
function fileTinyUpload(filePath: string): Promise<any> {
return fileUpload(filePath).then(data => fileUpdate(filePath, data));
}
function toSize(size: number): string {
if (size < 1024)
return size + 'B';
else if (size < 1048576)
return (size / 1024).toFixed(2) + 'KB';
else
return (size / 1024 / 1024).toFixed(2) + 'MB';
}
function toPercent(ratio: number): string {
return (100 * ratio).toFixed(2) + '%';
}