Files
Suzu008-ComfyUI-CryptIO/ts/utils/imageLoader.ts
T
Suzu008 05ac7e0542 refactor(utils): 重构加密文件处理工具模块
将加密文件处理相关功能拆分为独立工具模块,包括文件工具、上传工具、图片加载工具和加密工具

重构 cryptioSaveImage.ts 和 cryptioUploadImage.ts,使用新的工具模块替换原有代码
2025-10-12 06:34:57 +08:00

96 lines
2.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 图片加载模块
* 负责从服务器加载并解密图片用于预览
*/
import type { ComfyApi } from "@comfyorg/comfyui-frontend-types";
import { decryptFile } from "./cryptoUtils.js";
import { getMimeTypeFromFilename } from "./fileUtils.js";
export interface ImageLoadParams {
filename: string;
subfolder?: string;
type: string;
}
/**
* 从简单文件名加载加密图片(用于UploadImage场景)
* @param api ComfyUI API实例
* @param filename 文件名
* @returns Blob URL
*/
export async function loadEncryptedImageFromFilename(filename: string): Promise<string> {
// 从服务器获取加密数据(二进制格式)
const response = await fetch(
`/cryptio/view_encrypted?filename=${encodeURIComponent(filename)}`
);
if (!response.ok) {
throw new Error(`Failed to load encrypted image: ${response.statusText}`);
}
// 直接读取二进制数据
const encryptedArrayBuffer = await response.arrayBuffer();
const encryptedData = new Uint8Array(encryptedArrayBuffer);
// 解密数据
const decryptedData = await decryptFile(encryptedData);
// 转换为Blob URL
const blob = new Blob([new Uint8Array(decryptedData)], {
type: getMimeTypeFromFilename(filename),
});
return URL.createObjectURL(blob);
}
/**
* 从参数加载加密图片(用于SaveImage/PreviewImage场景)
* @param api ComfyUI API实例
* @param params 图片参数(包含filename, subfolder, type)
* @returns Blob URL
*/
export async function loadEncryptedImageFromParams(api: ComfyApi, params: ImageLoadParams): Promise<string> {
// 构建URL
const url = api.apiURL(
`/view?filename=${encodeURIComponent(params.filename)}&type=${params.type}${
params.subfolder ? `&subfolder=${encodeURIComponent(params.subfolder)}` : ""
}`
);
// 从服务器获取加密数据(二进制格式)
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to load encrypted image: ${response.statusText}`);
}
// 直接读取二进制数据
const encryptedArrayBuffer = await response.arrayBuffer();
const encryptedData = new Uint8Array(encryptedArrayBuffer);
// 解密数据
const decryptedData = await decryptFile(encryptedData);
// 转换为Blob URL
const blob = new Blob([new Uint8Array(decryptedData)], {
type: getMimeTypeFromFilename(params.filename),
});
return URL.createObjectURL(blob);
}
/**
* 下载解密后的图片
* @param blobUrl Blob URL
* @param filename 原始文件名(带 .encrypted 后缀)
*/
export function downloadDecryptedImage(blobUrl: string, filename: string): void {
const a = document.createElement("a");
a.href = blobUrl;
// 移除 .encrypted 后缀
const originalFilename = filename.replace(/\.encrypted$/, "");
a.download = originalFilename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}