| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217 |
- /**
- * 导出动画弹出框
- */
- class ExportView {
- constructor() {
- this.overlay = null;
- this.modal = null;
- this.previewImage = null;
- this.previewPlaceholder = null;
- this.referenceBox = null;
- this.referenceInput = null;
- this.referenceUploadArea = null;
- this.referenceImage = null;
- this.referenceImageWrapper = null;
- this.referenceRemoveBtn = null;
- this.replaceBtn = null;
- this.additionalPromptInput = null;
- this.cancelBtn = null;
- this.confirmBtn = null;
- this.imageData = null;
- this.referenceImageData = null;
- this.spritesheetCanvas = null;
- this.folderName = null;
- this.spritesheetLayout = null; // 保存布局信息用于生成 JSON
- this.replacedImageData = null; // 保存 Gemini 返回的替换后的图片(base64)
- this.geminiOriginalImageData = null; // 保存 Gemini 返回的原始图片(未抠图)
- this.originalSpritesheetData = null; // 保存原始 spritesheet 的 base64 数据
-
- // 下载确认对话框相关
- this.downloadConfirmOverlay = null;
- this.downloadConfirmClose = null;
- this.downloadOptions = null;
-
- this.init();
- }
- init() {
- this.overlay = document.getElementById('exportOverlay');
- this.modal = document.getElementById('exportModal');
- this.previewImage = document.getElementById('previewImage');
- this.previewPlaceholder = document.getElementById('previewPlaceholder');
- this.referenceBox = document.getElementById('referenceBox');
- this.referenceInput = document.getElementById('referenceInput');
- this.referenceUploadArea = document.getElementById('referenceUploadArea');
- this.referenceImage = document.getElementById('referenceImage');
- this.referenceImageWrapper = document.getElementById('referenceImageWrapper');
- this.referenceRemoveBtn = document.getElementById('referenceRemoveBtn');
- this.replaceBtn = document.getElementById('replaceBtn');
- this.additionalPromptInput = document.getElementById('additionalPromptInput');
- this.cancelBtn = document.getElementById('exportCancelBtn');
- this.confirmBtn = document.getElementById('exportConfirmBtn');
-
- // 下载确认对话框元素
- this.downloadConfirmOverlay = document.getElementById('downloadConfirmOverlay');
- this.downloadConfirmClose = document.getElementById('downloadConfirmClose');
- this.downloadOptions = document.querySelectorAll('.download-option');
-
- // 确保对话框初始状态是隐藏的
- if (this.downloadConfirmOverlay) {
- this.downloadConfirmOverlay.style.display = 'none';
- }
-
- this.bindEvents();
-
- // 初始时禁用确定按钮
- if (this.confirmBtn) {
- this.confirmBtn.disabled = true;
- }
-
- this.reset();
- }
- bindEvents() {
- // 取消按钮(右上角)
- this.cancelBtn?.addEventListener('click', () => {
- this.close();
- });
- // 取消按钮(底部操作栏)
- this.cancelBtnBottom?.addEventListener('click', () => {
- this.close();
- });
- // 确定按钮
- this.confirmBtn?.addEventListener('click', () => {
- this.handleConfirm();
- });
- // 替换按钮
- this.replaceBtn?.addEventListener('click', () => {
- this.replaceCharacter();
- });
- // 删除参考图按钮
- this.referenceRemoveBtn?.addEventListener('click', (e) => {
- e.stopPropagation(); // 阻止触发父元素的点击事件
- this.removeReferenceImage();
- });
- // 点击遮罩层关闭
- this.overlay?.addEventListener('click', (e) => {
- if (e.target === this.overlay) {
- this.close();
- }
- });
- // ESC键关闭
- document.addEventListener('keydown', (e) => {
- if (e.key === 'Escape') {
- if (this.downloadConfirmOverlay && this.downloadConfirmOverlay.style.display !== 'none') {
- this.hideDownloadConfirm();
- } else if (this.overlay) {
- this.close();
- }
- }
- });
-
- // 下载确认对话框事件
- this.downloadConfirmClose?.addEventListener('click', () => {
- this.hideDownloadConfirm();
- });
-
- // 点击遮罩层关闭下载确认对话框
- this.downloadConfirmOverlay?.addEventListener('click', (e) => {
- if (e.target === this.downloadConfirmOverlay) {
- this.hideDownloadConfirm();
- }
- });
-
- // 下载选项点击事件
- this.downloadOptions?.forEach(option => {
- option.addEventListener('click', () => {
- const downloadType = option.dataset.option;
- this.handleDownloadOption(downloadType);
- });
- });
- // 参考图上传区域点击
- this.referenceBox?.addEventListener('click', () => {
- this.referenceInput?.click();
- });
- // 参考图选择
- this.referenceInput?.addEventListener('change', (e) => {
- const file = e.target.files[0];
- if (file) {
- this.loadReferenceImage(file);
- }
- });
- // 拖拽上传参考图
- this.referenceBox?.addEventListener('dragover', (e) => {
- e.preventDefault();
- e.stopPropagation();
- if (this.referenceBox) {
- this.referenceBox.style.borderColor = '#667eea';
- }
- });
- this.referenceBox?.addEventListener('dragleave', (e) => {
- e.preventDefault();
- e.stopPropagation();
- if (this.referenceBox) {
- this.referenceBox.style.borderColor = '#e5e7eb';
- }
- });
- this.referenceBox?.addEventListener('drop', (e) => {
- e.preventDefault();
- e.stopPropagation();
- if (this.referenceBox) {
- this.referenceBox.style.borderColor = '#e5e7eb';
- }
-
- const file = e.dataTransfer.files[0];
- if (file && file.type.startsWith('image/')) {
- this.loadReferenceImage(file);
- }
- });
- // 监听来自父窗口的消息
- window.addEventListener('message', (event) => {
- if (event.data && event.data.type === 'show-export-preview') {
- // console.log('[ExportView] 收到显示预览消息:', event.data);
- this.showPreview(event.data.imageUrl || event.data.imageData);
- } else if (event.data && event.data.type === 'generate-export-preview') {
- // console.log('[ExportView] 收到生成预览消息:', event.data);
- this.reset();
- this.folderName = event.data.folderName;
- this.generatePreview(event.data.folderName);
- }
- });
- }
- /**
- * 生成预览图
- * @param {string} folderName - 文件夹名称
- */
- async generatePreview(folderName) {
- if (!folderName) {
- // console.warn('[ExportView] 没有提供文件夹名称');
- if (this.previewPlaceholder) {
- this.previewPlaceholder.textContent = '没有提供文件夹名称';
- }
- return;
- }
- // 重置状态(确保每次打开都是全新状态)
- this.reset();
- // 保存文件夹名称
- this.folderName = folderName;
- // 显示加载状态
- if (this.previewPlaceholder) {
- this.previewPlaceholder.classList.remove('hide');
- }
- if (this.previewImage) {
- this.previewImage.classList.remove('show');
- }
- try {
- const TEXTURE_ROOT = "http://localhost:3000/disk_data";
-
- // 获取当前登录用户名
- const username = this.getCurrentUsername();
-
- // 获取帧列表
- const encodedFolderName = encodeURIComponent(folderName);
- let apiUrl = `http://localhost:3000/api/frames/${encodedFolderName}`;
- if (username) {
- apiUrl += `?username=${encodeURIComponent(username)}`;
- }
- const response = await fetch(apiUrl);
-
- if (!response.ok) {
- // 服务端返回错误,解析错误信息并显示
- const errorMessage = await this.handleServerError(response, '无法获取帧列表');
- throw new Error(errorMessage);
- }
-
- const data = await response.json();
- const frameNumbers = data.frames || [];
- const fileNames = data.fileNames || [];
-
- if (frameNumbers.length === 0) {
- throw new Error('该文件夹中没有图片');
- }
-
- // 加载所有图片
- const images = [];
- for (let i = 0; i < frameNumbers.length; i++) {
- const frameNum = frameNumbers[i];
- const pathSegments = folderName.split('/').map(seg => encodeURIComponent(seg));
- const encodedPath = pathSegments.join('/');
-
- // 如果有文件名列表,使用实际文件名;否则使用帧号构造文件名
- let imgSrc;
- if (fileNames[i]) {
- // 使用实际文件名
- imgSrc = `${TEXTURE_ROOT}/${encodedPath}/${encodeURIComponent(fileNames[i])}`;
- } else {
- // 回退到使用帧号构造文件名
- const frameName = frameNum.toString().padStart(2, '0');
- imgSrc = `${TEXTURE_ROOT}/${encodedPath}/${frameName}.png`;
- }
-
- const img = await new Promise((resolve, reject) => {
- const image = new Image();
- image.crossOrigin = 'anonymous';
- image.onload = () => resolve(image);
- image.onerror = () => reject(new Error(`Failed to load image: ${imgSrc}`));
- image.src = imgSrc;
- });
-
- images.push({
- img: img,
- width: img.width,
- height: img.height,
- frameNum: frameNum
- });
- }
-
- // 计算布局(简化版,使用简单的网格布局)
- const frameWidth = images[0].width;
- const frameHeight = images[0].height;
- const cols = Math.ceil(Math.sqrt(images.length));
- const rows = Math.ceil(images.length / cols);
-
- // 创建 Canvas 并绘制
- const canvas = document.createElement('canvas');
- canvas.width = frameWidth * cols;
- canvas.height = frameHeight * rows;
- const ctx = canvas.getContext('2d');
-
- // 保存 canvas 和布局信息用于下载
- this.spritesheetCanvas = canvas;
-
- // 填充透明背景
- ctx.clearRect(0, 0, canvas.width, canvas.height);
-
- // 保存布局信息(用于生成 JSON)
- const layout = [];
-
- // 绘制所有图片
- images.forEach((item, index) => {
- const col = index % cols;
- const row = Math.floor(index / cols);
- const x = col * frameWidth;
- const y = row * frameHeight;
- ctx.drawImage(item.img, x, y);
-
- // 保存布局信息
- layout.push({
- x: x,
- y: y,
- width: item.width,
- height: item.height,
- frameNum: item.frameNum
- });
- });
-
- // 保存布局信息
- this.spritesheetLayout = {
- layout: layout,
- sheetWidth: canvas.width,
- sheetHeight: canvas.height
- };
-
- // 转换为 base64
- const imageUrl = await new Promise((resolve) => {
- canvas.toBlob((blob) => {
- const url = URL.createObjectURL(blob);
- resolve(url);
- }, 'image/png');
- });
-
- // 保存原始 spritesheet 的 base64 数据
- this.originalSpritesheetData = await new Promise((resolve) => {
- canvas.toBlob((blob) => {
- const reader = new FileReader();
- reader.onload = () => resolve(reader.result);
- reader.readAsDataURL(blob);
- }, 'image/png');
- });
-
- // 显示预览图
- this.showPreview(imageUrl);
-
- // 如果已经有参考图,显示替换按钮
- if (this.referenceImageData && this.replaceBtn) {
- this.replaceBtn.style.display = 'block';
- }
-
- // 移除自动调用替换 API 的逻辑
- } catch (error) {
- // console.error('[ExportView] 生成预览图失败:', error);
- if (this.previewPlaceholder) {
- // 隐藏加载动画,显示错误信息
- const spinner = this.previewPlaceholder.querySelector('.loading-spinner');
- const loadingText = this.previewPlaceholder.querySelector('.loading-text');
- if (spinner) spinner.style.display = 'none';
- if (loadingText) {
- loadingText.textContent = '生成预览图失败: ' + error.message;
- loadingText.style.color = '#ef4444';
- }
- this.previewPlaceholder.classList.remove('hide');
- }
- }
- }
- /**
- * 计算宽高比
- * @param {number} width - 宽度
- * @param {number} height - 高度
- * @returns {string} 宽高比字符串(例如:16:9)
- */
- calculateAspectRatio(width, height) {
- // 计算最大公约数
- const gcd = (a, b) => b === 0 ? a : gcd(b, a % b);
- const divisor = gcd(width, height);
- const ratioWidth = width / divisor;
- const ratioHeight = height / divisor;
-
- // 如果比例太大,使用简化版本
- if (ratioWidth > 100 || ratioHeight > 100) {
- // 使用小数形式
- const ratio = width / height;
- return ratio.toFixed(2) + ':1';
- }
-
- return `${ratioWidth}:${ratioHeight}`;
- }
- /**
- * 加载参考图
- * @param {File} file - 图片文件
- */
- loadReferenceImage(file) {
- const reader = new FileReader();
- reader.onload = (e) => {
- this.referenceImageData = e.target.result;
- if (this.referenceImage) {
- this.referenceImage.src = e.target.result;
- }
- if (this.referenceImageWrapper) {
- this.referenceImageWrapper.style.display = 'flex';
- }
- if (this.referenceUploadArea) {
- this.referenceUploadArea.classList.add('hide');
- }
-
- // 显示替换按钮和提示词配置区域(如果已经有 spritesheet)
- if (this.originalSpritesheetData) {
- if (this.replaceBtn) {
- this.replaceBtn.style.display = 'block';
- }
- // 显示提示词配置区域
- const promptConfigSection = document.getElementById('promptConfigSection');
- if (promptConfigSection) {
- promptConfigSection.style.display = 'flex';
- }
- }
-
- // 移除自动调用替换 API 的逻辑
- };
- reader.readAsDataURL(file);
- }
- /**
- * 删除参考图
- */
- removeReferenceImage() {
- // 清空参考图数据
- this.referenceImageData = null;
- this.replacedImageData = null; // 同时清空替换后的图片
- // 隐藏参考图,显示上传区域
- if (this.referenceImageWrapper) {
- this.referenceImageWrapper.style.display = 'none';
- }
- if (this.referenceImage) {
- this.referenceImage.src = '';
- }
- if (this.referenceUploadArea) {
- this.referenceUploadArea.classList.remove('hide');
- }
- if (this.referenceInput) {
- this.referenceInput.value = '';
- }
- // 隐藏替换按钮和提示词配置区域
- if (this.replaceBtn) {
- this.replaceBtn.style.display = 'none';
- this.replaceBtn.disabled = false;
- }
- const promptConfigSection = document.getElementById('promptConfigSection');
- if (promptConfigSection) {
- promptConfigSection.style.display = 'none';
- }
- // 如果预览图是替换后的图片,恢复显示原始 spritesheet
- if (this.replacedImageData && this.originalSpritesheetData) {
- // 清空替换后的图片,恢复显示原始预览
- this.replacedImageData = null;
- // 重新显示原始 spritesheet
- if (this.spritesheetCanvas) {
- this.spritesheetCanvas.toBlob((blob) => {
- const url = URL.createObjectURL(blob);
- this.showPreview(url);
- }, 'image/png');
- }
- }
- }
- /**
- * 调用角色替换 API
- */
- async replaceCharacter() {
- if (!this.originalSpritesheetData || !this.referenceImageData) {
- this.showAlert('请先上传参考图和生成 Spritesheet');
- return;
- }
- // 禁用替换按钮和下载按钮
- if (this.replaceBtn) {
- this.replaceBtn.disabled = true;
- }
- if (this.confirmBtn) {
- this.confirmBtn.disabled = true;
- }
- try {
- // 显示加载状态
- if (this.previewPlaceholder) {
- const spinner = this.previewPlaceholder.querySelector('.loading-spinner');
- const loadingText = this.previewPlaceholder.querySelector('.loading-text');
- if (spinner) spinner.style.display = 'block';
- if (loadingText) {
- loadingText.textContent = '正在生成替换后的图片...';
- loadingText.style.color = '#6b7280';
- }
- this.previewPlaceholder.classList.remove('hide');
- }
- if (this.previewImage) {
- this.previewImage.classList.remove('show');
- }
- // 准备图片数据(移除 data:image/png;base64, 前缀)
- const image1Base64 = this.originalSpritesheetData.replace(/^data:image\/\w+;base64,/, '');
- const image2Base64 = this.referenceImageData.replace(/^data:image\/\w+;base64,/, '');
- // 获取 image1 的尺寸
- const image1Width = this.spritesheetLayout?.sheetWidth || 0;
- const image1Height = this.spritesheetLayout?.sheetHeight || 0;
-
- // 获取额外提示词
- const additionalPrompt = this.additionalPromptInput?.value || '';
- // 调用 API
- const response = await fetch('http://localhost:3000/api/replace-character', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({
- image1: image1Base64,
- image2: image2Base64,
- image1Width: image1Width,
- image1Height: image1Height,
- additionalPrompt: additionalPrompt
- })
- });
- if (!response.ok) {
- const errorMessage = await this.handleServerError(response, '角色替换失败');
- throw new Error(errorMessage);
- }
- const result = await response.json();
-
- if (result.success && result.imageData) {
- // Gemini 返回的图片 base64(不进行抠图,直接保存原始图片)
- const geminiImageBase64 = result.imageData;
-
- // 保存 Gemini 返回的原始图片(不抠图)
- this.geminiOriginalImageData = `data:image/png;base64,${geminiImageBase64}`;
- this.replacedImageData = this.geminiOriginalImageData; // 用于显示预览
-
- // 显示原始图片(不抠图)
- this.showPreview(this.geminiOriginalImageData);
- } else {
- throw new Error('API 返回失败或未找到图片数据');
- }
- } catch (error) {
- // console.error('[ExportView] 替换角色失败:', error);
- if (this.previewPlaceholder) {
- const spinner = this.previewPlaceholder.querySelector('.loading-spinner');
- const loadingText = this.previewPlaceholder.querySelector('.loading-text');
- if (spinner) spinner.style.display = 'none';
- if (loadingText) {
- loadingText.textContent = '替换失败: ' + error.message;
- loadingText.style.color = '#ef4444';
- }
- this.previewPlaceholder.classList.remove('hide');
- }
- } finally {
- // 重新启用替换按钮和下载按钮
- if (this.replaceBtn) {
- this.replaceBtn.disabled = false;
- }
- if (this.confirmBtn) {
- this.confirmBtn.disabled = false;
- }
- }
- }
- /**
- * 显示预览图(Spritesheet)
- * @param {string} imageUrl - 图片URL或base64数据
- */
- showPreview(imageUrl) {
- if (!imageUrl) {
- // console.warn('[ExportView] 没有提供图片数据');
- return;
- }
- // console.log('[ExportView] 显示预览图');
-
- // 保存图片数据
- this.imageData = imageUrl;
-
- // 图片加载前禁用下载按钮
- if (this.confirmBtn) {
- this.confirmBtn.disabled = true;
- }
-
- // 加载图片
- const img = new Image();
- img.onload = () => {
- if (this.previewImage) {
- this.previewImage.src = imageUrl;
- this.previewImage.classList.add('show');
- }
- if (this.previewPlaceholder) {
- this.previewPlaceholder.classList.add('hide');
- }
- // 图片加载完成后启用下载按钮
- if (this.confirmBtn) {
- this.confirmBtn.disabled = false;
- }
- // console.log('[ExportView] ✓ 预览图已加载');
- };
-
- img.onerror = () => {
- // 图片加载失败时禁用下载按钮
- if (this.confirmBtn) {
- this.confirmBtn.disabled = true;
- }
- // console.error('[ExportView] 图片加载失败');
- if (this.previewPlaceholder) {
- // 隐藏加载动画,显示错误信息
- const spinner = this.previewPlaceholder.querySelector('.loading-spinner');
- const loadingText = this.previewPlaceholder.querySelector('.loading-text');
- if (spinner) spinner.style.display = 'none';
- if (loadingText) {
- loadingText.textContent = '图片加载失败';
- loadingText.style.color = '#ef4444';
- }
- this.previewPlaceholder.classList.remove('hide');
- }
- };
-
- img.src = imageUrl;
- }
- /**
- * 生成 JSON 数据
- * @param {string} folderName - 文件夹名称
- * @param {Array} layout - 布局信息数组
- * @param {number} sheetWidth - Spritesheet 宽度
- * @param {number} sheetHeight - Spritesheet 高度
- * @returns {string} JSON 字符串
- */
- generateJSON(folderName, layout, sheetWidth, sheetHeight) {
- const frames = {};
-
- layout.forEach((item, index) => {
- // 使用实际的帧号,确保与原始文件名一致
- const frameNum = item.frameNum ? item.frameNum.toString().padStart(2, '0') : (index + 1).toString().padStart(2, '0');
- const frameName = `${frameNum}.png`;
- const x = item.x;
- const y = item.y;
- const width = item.width;
- const height = item.height;
-
- // 标准的 TexturePacker JSON 格式,Cocos Creator 3.8 完全兼容
- frames[frameName] = {
- frame: {
- x: x,
- y: y,
- w: width,
- h: height
- },
- rotated: false,
- trimmed: false,
- spriteSourceSize: { x: 0, y: 0, w: width, h: height },
- sourceSize: { w: width, h: height }
- };
- });
- // Cocos Creator 3.8 兼容的 TexturePacker JSON 格式
- const json = {
- frames: frames,
- meta: {
- app: "https://www.codeandweb.com/texturepacker",
- version: "1.0",
- image: `${folderName}.png`,
- format: "RGBA8888",
- size: { w: sheetWidth, h: sheetHeight },
- scale: 1
- }
- };
- return JSON.stringify(json, null, 2);
- }
- /**
- * 将 Blob 转换为 Base64
- * @param {Blob} blob - Blob 对象
- * @returns {Promise<string>} Base64 字符串
- */
- blobToBase64(blob) {
- return new Promise((resolve, reject) => {
- const reader = new FileReader();
- reader.onloadend = () => {
- try {
- let base64 = reader.result;
- // 移除 data:image/png;base64, 前缀(如果存在)
- if (base64 && base64.includes(',')) {
- base64 = base64.split(',')[1];
- }
- if (!base64) {
- reject(new Error('Base64 转换失败:结果为空'));
- return;
- }
- resolve(base64);
- } catch (error) {
- reject(new Error(`Base64 转换失败: ${error.message}`));
- }
- };
- reader.onerror = () => {
- reject(new Error('文件读取失败'));
- };
- reader.readAsDataURL(blob);
- });
- }
- /**
- * 下载文件
- * @param {Blob} data - 文件数据
- * @param {string} filename - 文件名
- * @param {string} mimeType - MIME 类型
- */
- downloadFile(data, filename, mimeType) {
- const blob = new Blob([data], { type: mimeType });
- const url = URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.href = url;
- a.download = filename;
- document.body.appendChild(a);
- a.click();
- document.body.removeChild(a);
- URL.revokeObjectURL(url);
- }
- /**
- * 显示下载确认对话框
- */
- showDownloadConfirm() {
- if (this.downloadConfirmOverlay) {
- console.log('[ExportView] 显示下载确认对话框');
- this.downloadConfirmOverlay.style.display = 'flex';
- } else {
- console.error('[ExportView] 下载确认对话框元素未找到');
- }
- }
- /**
- * 隐藏下载确认对话框
- */
- hideDownloadConfirm() {
- if (this.downloadConfirmOverlay) {
- this.downloadConfirmOverlay.style.display = 'none';
- }
- }
- /**
- * 处理下载选项选择
- * @param {string} downloadType - 下载类型:'original', 'normal', 'vip'
- */
- async handleDownloadOption(downloadType) {
- this.hideDownloadConfirm();
-
- try {
- // 显示加载状态(但不隐藏预览图片)
- // 使用全局 Loading 提示,不干扰预览图显示
- if (window.parent && window.parent.postMessage) {
- window.parent.postMessage({
- type: 'global-loading',
- action: 'show',
- text: downloadType === 'original' ? '正在准备下载...' : '正在处理图片...'
- }, '*');
- }
-
- let processedImageBase64;
-
- // 确定使用的图片源
- if (this.geminiOriginalImageData) {
- // 如果有 Gemini 图片,使用 Gemini 图片
- const geminiImageBase64 = this.geminiOriginalImageData.replace(/^data:image\/\w+;base64,/, '');
-
- if (downloadType === 'original') {
- // 源文件下载:直接使用原始图片
- processedImageBase64 = geminiImageBase64;
- } else if (downloadType === 'normal') {
- // 普通抠图:调用 rembg-matting.py
- const response = await fetch('http://localhost:3000/api/matting-normal', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({
- imageBase64: geminiImageBase64
- })
- });
-
- if (!response.ok) {
- const errorMessage = await this.handleServerError(response, '普通抠图失败');
- throw new Error(errorMessage);
- }
-
- const result = await response.json();
- if (!result.success || !result.imageData) {
- throw new Error('普通抠图处理失败');
- }
-
- processedImageBase64 = result.imageData;
- } else if (downloadType === 'vip') {
- // VIP抠图:调用 BiRefNet
- const response = await fetch('http://localhost:3000/api/matting-vip', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({
- imageBase64: geminiImageBase64
- })
- });
-
- if (!response.ok) {
- const errorMessage = await this.handleServerError(response, 'VIP抠图失败');
- throw new Error(errorMessage);
- }
-
- const result = await response.json();
- if (!result.success || !result.imageData) {
- throw new Error('VIP抠图处理失败');
- }
-
- processedImageBase64 = result.imageData;
- }
- } else {
- // 如果没有 Gemini 图片,使用原始 spritesheet
- const imageBlob = await new Promise((resolve, reject) => {
- this.spritesheetCanvas.toBlob((blob) => {
- if (blob) {
- resolve(blob);
- } else {
- reject(new Error('Canvas 转换失败'));
- }
- }, 'image/png');
- });
-
- // 将图片转换为 Base64
- const originalImageBase64 = await this.blobToBase64(imageBlob);
-
- if (downloadType === 'original') {
- // 源文件下载:直接使用原始 spritesheet
- processedImageBase64 = originalImageBase64;
- } else if (downloadType === 'normal') {
- // 普通抠图:对原始 spritesheet 进行抠图
- const response = await fetch('http://localhost:3000/api/matting-normal', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({
- imageBase64: originalImageBase64
- })
- });
-
- if (!response.ok) {
- const errorMessage = await this.handleServerError(response, '普通抠图失败');
- throw new Error(errorMessage);
- }
-
- const result = await response.json();
- if (!result.success || !result.imageData) {
- throw new Error('普通抠图处理失败');
- }
-
- processedImageBase64 = result.imageData;
- } else if (downloadType === 'vip') {
- // VIP抠图:对原始 spritesheet 进行 VIP 抠图
- const response = await fetch('http://localhost:3000/api/matting-vip', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({
- imageBase64: originalImageBase64
- })
- });
-
- if (!response.ok) {
- const errorMessage = await this.handleServerError(response, 'VIP抠图失败');
- throw new Error(errorMessage);
- }
-
- const result = await response.json();
- if (!result.success || !result.imageData) {
- throw new Error('VIP抠图处理失败');
- }
-
- processedImageBase64 = result.imageData;
- }
- }
-
- // 生成 JSON 数据
- const folderName = this.folderName.split('/').pop() || 'spritesheet';
- const jsonData = this.generateJSON(
- folderName,
- this.spritesheetLayout.layout,
- this.spritesheetLayout.sheetWidth,
- this.spritesheetLayout.sheetHeight
- );
-
- // 发送到服务器打包
- const response = await fetch('http://localhost:3000/api/pack', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({
- folderName: folderName,
- imageData: processedImageBase64,
- jsonData: jsonData
- })
- });
- if (!response.ok) {
- const errorMessage = await this.handleServerError(response, '打包失败');
- throw new Error(errorMessage);
- }
- // 获取 ZIP 文件的 Blob
- const zipBlob = await response.blob();
-
- // 下载 ZIP 文件
- this.downloadFile(zipBlob, `${folderName}.zip`, 'application/zip');
-
- // 隐藏全局 Loading 提示
- if (window.parent && window.parent.postMessage) {
- window.parent.postMessage({
- type: 'global-loading',
- action: 'hide'
- }, '*');
- }
-
- // 下载完成后,不关闭弹出框,不刷新图片
- // 显示成功提示
- this.showAlert('下载成功!');
- } catch (error) {
- // console.error('[ExportView] 下载失败:', error);
-
- // 隐藏全局 Loading 提示
- if (window.parent && window.parent.postMessage) {
- window.parent.postMessage({
- type: 'global-loading',
- action: 'hide'
- }, '*');
- }
-
- this.showAlert(`下载失败: ${error.message}`);
- }
- }
- /**
- * 处理下载按钮点击
- */
- async handleConfirm() {
- // console.log('[ExportView] 用户点击下载按钮');
-
- if (!this.spritesheetCanvas || !this.spritesheetLayout) {
- // console.warn('[ExportView] 没有可下载的 Spritesheet');
- return;
- }
-
- // 总是显示下载确认对话框,让用户选择下载方式
- console.log('[ExportView] 显示下载选项对话框');
- this.showDownloadConfirm();
- }
-
- /**
- * 下载 Spritesheet(原始逻辑)
- */
- async downloadSpritesheet() {
- try {
- // 生成 JSON 数据
- const folderName = this.folderName.split('/').pop() || 'spritesheet';
- const jsonData = this.generateJSON(
- folderName,
- this.spritesheetLayout.layout,
- this.spritesheetLayout.sheetWidth,
- this.spritesheetLayout.sheetHeight
- );
-
- // 确定使用哪个图片:如果有替换后的图片,使用替换后的;否则使用原始的
- let imageBase64;
- if (this.replacedImageData) {
- // 使用替换后的图片(移除 data:image/png;base64, 前缀)
- imageBase64 = this.replacedImageData.replace(/^data:image\/\w+;base64,/, '');
- } else {
- // 使用原始 spritesheet
- const imageBlob = await new Promise((resolve, reject) => {
- this.spritesheetCanvas.toBlob((blob) => {
- if (blob) {
- resolve(blob);
- } else {
- reject(new Error('Canvas 转换失败'));
- }
- }, 'image/png');
- });
-
- // 将图片转换为 Base64
- imageBase64 = await this.blobToBase64(imageBlob);
- }
-
- // 验证数据
- if (!imageBase64 || typeof imageBase64 !== 'string' || imageBase64.trim().length === 0) {
- throw new Error('图片数据无效');
- }
-
- if (!jsonData || typeof jsonData !== 'string' || jsonData.trim().length === 0) {
- throw new Error('JSON 数据无效');
- }
-
- // 发送到服务器打包
- const response = await fetch('http://localhost:3000/api/pack', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({
- folderName: folderName,
- imageData: imageBase64,
- jsonData: jsonData
- })
- });
- if (!response.ok) {
- const errorMessage = await this.handleServerError(response, '打包失败');
- throw new Error(errorMessage);
- }
- // 获取 ZIP 文件的 Blob
- const zipBlob = await response.blob();
-
- // 下载 ZIP 文件
- this.downloadFile(zipBlob, `${folderName}.zip`, 'application/zip');
-
- // 下载完成后,不关闭弹出框,不刷新图片
- // 显示成功提示
- this.showAlert('下载成功!');
- } catch (error) {
- // console.error('[ExportView] 下载失败:', error);
- this.showAlert(`下载失败: ${error.message}`);
- }
- }
- /**
- * 关闭弹出框
- */
- close() {
- // console.log('[ExportView] 关闭导出弹出框');
-
- // 清空所有数据
- this.reset();
-
- // 通知父窗口关闭弹出框
- if (window.parent && window.parent !== window) {
- window.parent.postMessage({
- type: 'close-export-view'
- }, '*');
- }
- }
- /**
- * 获取当前登录用户名
- */
- getCurrentUsername() {
- try {
- const loginDataStr = localStorage.getItem('loginData');
- if (!loginDataStr) {
- return null;
- }
-
- const loginData = JSON.parse(loginDataStr);
- const now = Date.now();
-
- // 检查是否过期
- if (now >= loginData.expireTime) {
- localStorage.removeItem('loginData');
- return null;
- }
-
- return loginData.user ? loginData.user.username : null;
- } catch (error) {
- console.error('[ExportView] 获取用户名失败:', error);
- return null;
- }
- }
- /**
- * 重置所有数据和UI状态
- */
- reset() {
- // 清空数据属性
- this.imageData = null;
- this.referenceImageData = null;
- this.spritesheetCanvas = null;
- this.folderName = null;
- this.spritesheetLayout = null;
- this.replacedImageData = null;
- this.geminiOriginalImageData = null;
- this.originalSpritesheetData = null;
- // 重置参考图区域
- if (this.referenceImageWrapper) {
- this.referenceImageWrapper.style.display = 'none';
- }
- if (this.referenceImage) {
- this.referenceImage.src = '';
- }
- if (this.referenceUploadArea) {
- this.referenceUploadArea.classList.remove('hide');
- }
- if (this.referenceInput) {
- this.referenceInput.value = '';
- }
- if (this.replaceBtn) {
- this.replaceBtn.style.display = 'none';
- this.replaceBtn.disabled = false;
- }
- // 重置预览图区域
- if (this.previewImage) {
- this.previewImage.src = '';
- this.previewImage.classList.remove('show');
- }
- if (this.previewPlaceholder) {
- const spinner = this.previewPlaceholder.querySelector('.loading-spinner');
- const loadingText = this.previewPlaceholder.querySelector('.loading-text');
- if (spinner) spinner.style.display = 'block';
- if (loadingText) {
- loadingText.textContent = '正在生成预览图...';
- loadingText.style.color = '#6b7280';
- }
- this.previewPlaceholder.classList.remove('hide');
- }
- // 重置提示词配置区域
- const promptConfigSection = document.getElementById('promptConfigSection');
- if (promptConfigSection) {
- promptConfigSection.style.display = 'none';
- }
- if (this.additionalPromptInput) {
- this.additionalPromptInput.value = '';
- }
- // 重置按钮状态
- if (this.confirmBtn) {
- this.confirmBtn.disabled = true;
- }
- }
- /**
- * 显示提示信息(使用全局 Alert 组件,直接调用)
- * @param {string} message - 提示信息
- * @param {number} duration - 显示时长(毫秒),默认2000
- */
- showAlert(message, duration = 2000) {
- // 直接调用父窗口的 GlobalAlert(不通过 postMessage)
- try {
- // 优先使用父窗口的 GlobalAlert
- if (window.parent && window.parent !== window && window.parent.GlobalAlert) {
- window.parent.GlobalAlert.show(message, duration);
- return;
- }
-
- // 如果不在 iframe 中,直接使用当前窗口的 GlobalAlert
- if (window.GlobalAlert) {
- window.GlobalAlert.show(message, duration);
- return;
- }
-
- // 降级处理
- console.log('[Alert]', message);
- } catch (error) {
- console.error('[ExportView] 显示 alert 失败:', error);
- alert(message);
- }
- }
- // 统一的错误处理函数:解析服务端错误响应并显示
- async handleServerError(response, defaultMessage = '操作失败') {
- let errorMessage = defaultMessage;
-
- try {
- // 尝试解析 JSON 错误响应
- const errorData = await response.json().catch(() => null);
- if (errorData) {
- // 优先使用服务端返回的 message
- if (errorData.message) {
- errorMessage = errorData.message;
- } else if (errorData.error) {
- errorMessage = errorData.error;
- } else if (typeof errorData === 'string') {
- errorMessage = errorData;
- }
- }
- } catch (e) {
- // 如果解析失败,使用默认消息或状态码
- if (response.status) {
- errorMessage = `${defaultMessage} (状态码: ${response.status})`;
- }
- }
-
- this.showAlert(errorMessage);
- return errorMessage;
- }
- }
- // 初始化
- window.ExportView = new ExportView();
|