1 Commits

Author SHA1 Message Date
454c938728 v1.2.3: 执行操作后保持当前配置面板 2026-04-21 12:59:49 +08:00
7 changed files with 163 additions and 352 deletions

10
app.py
View File

@@ -1,7 +1,7 @@
"""
图片编辑器 - Image Editor v1.2.7
图片编辑器 - Image Editor v1.2.3
前端图片处理工具:合并、分割、挖孔填充、圆形切图、文字图片等
v1.2.7: 修复合并图片紧密拼接问题
v1.2.3: 执行操作后保持当前配置面板
端口: 19018
"""
@@ -25,7 +25,7 @@ def index():
@app.route('/api/health')
def health():
return jsonify({'status': 'ok', 'version': '1.2.7', 'time': datetime.now().isoformat()})
return jsonify({'status': 'ok', 'version': '1.2.2', 'time': datetime.now().isoformat()})
@app.route('/api/save', methods=['POST'])
def save_image():
@@ -64,9 +64,9 @@ def list_images():
if __name__ == '__main__':
print("=" * 50)
print("图片编辑器 - Image Editor v1.2.7")
print("图片编辑器 - Image Editor v1.2.2")
print("=" * 50)
print("修复合并图片紧密拼接问题")
print("右侧面板始终显示,首页显示快捷入口")
print(f"访问地址: http://localhost:19018")
print("=" * 50)
app.run(host='0.0.0.0', port=19018, debug=True)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 763 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 763 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 768 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 767 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 796 KiB

View File

@@ -3,7 +3,7 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图片编辑器 - Image Editor v1.2.7</title>
<title>图片编辑器 - Image Editor v1.2.3</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://cdn.jsdelivr.net/npm/remixicon@3.5.0/fonts/remixicon.css" rel="stylesheet">
<style>
@@ -87,9 +87,12 @@
</button>
</div>
</div>
<!-- 功能按钮 -->
<div class="mt-3 flex gap-2 flex-wrap">
<button onclick="setTool('upload')" id="tool-upload" class="tool-btn px-3 py-2 bg-gray-200 rounded-lg">
<i class="ri-upload-cloud-line mr-1"></i>上传图片
</button>
<button onclick="setTool('merge')" id="tool-merge" class="tool-btn px-3 py-2 bg-gray-200 rounded-lg">
<i class="ri-stack-line mr-1"></i>合并图片
</button>
@@ -124,17 +127,16 @@
<canvas id="mainCanvas"></canvas>
<div id="emptyHint" class="text-gray-400 text-center">
<i class="ri-image-add-line text-6xl"></i>
<p class="mt-2">拖动图片到此处上传</p>
<p class="text-sm mt-1">支持多张图片同时上传</p>
<p class="mt-2">点击"上传图片"或拖放图片开始编辑</p>
</div>
</div>
<!-- 图片列表 -->
<div id="imageList" class="mt-4 hidden">
<h3 class="text-sm font-medium text-gray-600 mb-2">已加载图片 <span id="imageCount">(0张)</span></h3>
<div id="imageItems" class="flex gap-2 overflow-x-auto pb-2"></div>
</div>
<!-- 分割结果展示 -->
<div id="splitResults" class="mt-4 hidden">
<h3 class="text-sm font-medium text-gray-600 mb-2">分割结果</h3>
@@ -149,10 +151,10 @@
<div class="flex items-center justify-between mb-4">
<h2 id="panelTitle" class="font-bold text-gray-800">操作面板</h2>
</div>
<!-- 配置内容区域 -->
<div id="panelContent"></div>
<!-- 操作按钮 -->
<div id="panelActions" class="mt-4 pt-4 border-t"></div>
</div>
@@ -183,143 +185,18 @@
selection: null,
textStyles: { bold: false, italic: false },
mergeImageOrder: [],
mergeImageSizes: {},
previewMode: false, // 预览模式
previewData: null, // 预览图片数据
originalImages: null // 预览前保存的原始图片
mergeImageSizes: {}
};
const canvas = document.getElementById('mainCanvas');
const ctx = canvas.getContext('2d');
const container = document.getElementById('canvasContainer');
// 检查是否有图片(画布有内容)
function hasImage() {
return state.images.length > 0 || document.getElementById('emptyHint').classList.contains('hidden');
}
// 显示预览效果(操作后显示结果,但保留原始图片)
function showPreviewResult(dataUrl, name) {
// 进入预览模式
state.previewMode = true;
state.previewData = dataUrl;
// 保存原始图片状态
state.originalImages = state.images.map(img => ({
...img,
// 不复制img对象只保存数据
}));
// 显示预览效果(追加结果图片,不清除原始)
const img = new Image();
img.onload = () => {
// 调整画布大小以适应结果图片
canvas.width = img.width;
canvas.height = img.height;
// 绘制结果图片
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0);
hideEmptyHint();
// 显示预览面板
showPreviewPanel(name);
};
img.src = dataUrl;
}
// 显示预览面板
function showPreviewPanel(operationName) {
document.getElementById('panelTitle').textContent = '预览效果';
document.getElementById('panelContent').innerHTML = `
<div class="space-y-3">
<div class="p-3 bg-green-50 rounded-lg">
<p class="text-sm text-green-700">
<i class="ri-check-line"></i> ${operationName} 完成!
</p>
<p class="text-xs text-green-600 mt-1">预览效果已显示,原图片仍保留</p>
</div>
<p class="text-xs text-gray-500">选择"应用结果"替换原图,或"取消"恢复</p>
</div>
`;
document.getElementById('panelActions').innerHTML = `
<button onclick="applyPreviewResult()" class="px-4 py-2 bg-green-500 text-white rounded-lg w-full mb-2">
<i class="ri-check-double-line mr-1"></i>应用结果
</button>
<button onclick="cancelPreview()" class="px-4 py-2 bg-gray-200 rounded-lg w-full mb-2">
<i class="ri-close-line mr-1"></i>取消预览
</button>
<button onclick="goHome()" class="px-4 py-2 bg-blue-100 text-blue-600 rounded-lg w-full">
<i class="ri-home-line mr-1"></i>返回首页
</button>
`;
}
// 应用预览结果
function applyPreviewResult() {
if (!state.previewData) return;
// 清空原始图片,只保留结果
state.images = [];
const img = new Image();
img.onload = () => {
state.images.push({
img: img,
name: 'result_' + Date.now(),
x: 0,
y: 0,
width: img.width,
height: img.height,
dataUrl: state.previewData
});
drawCanvas();
updateImageList();
saveState('应用结果');
// 清除预览状态
state.previewMode = false;
state.previewData = null;
state.originalImages = null;
// 返回首页
goHome();
};
img.src = state.previewData;
}
// 取消预览
function cancelPreview() {
if (!state.originalImages) {
goHome();
return;
}
// 恢复原始图片
state.images = [];
state.originalImages.forEach((item, idx) => {
if (state.images[idx] && state.images[idx].img) {
state.images.push(state.images[idx]);
}
});
// 如果没有恢复成功,重新从画布历史恢复
if (state.images.length === 0 && state.historyStack.length > 0) {
const lastState = state.historyStack[state.historyStack.length - 1];
restoreState(lastState);
} else {
drawCanvas();
updateImageList();
}
// 清除预览状态
state.previewMode = false;
state.previewData = null;
state.originalImages = null;
// 返回首页
goHome();
// 返回首页面板
function goHome() {
document.querySelectorAll('.tool-btn').forEach(btn => btn.classList.remove('active'));
state.currentTool = null;
showPanel('home');
}
// 刷新当前工具面板(执行操作后保持当前配置)
@@ -359,15 +236,20 @@
function setTool(tool) {
// 移除所有工具的 active 状态
document.querySelectorAll('.tool-btn').forEach(btn => btn.classList.remove('active'));
// 设置当前工具 active
const btn = document.getElementById('tool-' + tool);
if (btn) btn.classList.add('active');
state.currentTool = tool;
// 更新右侧配置面板内容(不隐藏)
showPanel(tool);
// 上传图片直接触发文件选择
if (tool === 'upload') {
document.getElementById('fileInput').click();
}
}
// 显示右侧面板内容
@@ -375,7 +257,7 @@
const panel = document.getElementById('rightPanel');
// 确保面板始终显示
panel.classList.remove('hidden-panel');
const configs = getPanelConfig(tool);
document.getElementById('panelTitle').textContent = configs.title;
document.getElementById('panelContent').innerHTML = configs.content;
@@ -384,18 +266,18 @@
// 获取各工具的配置面板内容
function getPanelConfig(tool) {
<!-- 默认首页面板 -->
// 默认首页面板
if (!tool || tool === 'home') {
return {
title: '欢迎使用',
content: `
<div class="space-y-4">
<p class="text-sm text-gray-600">点击顶部功能按钮开始编辑图片</p>
<div class="p-3 bg-blue-50 rounded-lg border-2 border-dashed border-blue-300 text-center">
<i class="ri-upload-cloud-2-line text-3xl text-blue-500"></i>
<p class="text-sm text-blue-600 mt-2">拖动图片到左侧画布区域上传</p>
</div>
<div class="grid grid-cols-2 gap-2">
<button onclick="setTool('upload')" class="p-3 bg-blue-50 rounded-lg hover:bg-blue-100 text-center">
<i class="ri-upload-cloud-line text-2xl text-blue-500"></i>
<p class="text-xs mt-1">上传图片</p>
</button>
<button onclick="setTool('merge')" class="p-3 bg-green-50 rounded-lg hover:bg-green-100 text-center">
<i class="ri-stack-line text-2xl text-green-500"></i>
<p class="text-xs mt-1">合并图片</p>
@@ -434,18 +316,29 @@
actions: ''
};
}
switch(tool) {
case 'upload':
return {
title: '上传图片',
content: `
<p class="text-sm text-gray-600 mb-4">点击按钮选择图片,或直接拖放图片到画布区域</p>
<button onclick="document.getElementById('fileInput').click()" class="w-full px-4 py-3 bg-blue-500 text-white rounded-lg">
<i class="ri-upload-cloud-line mr-2"></i>选择图片
</button>
`,
actions: ''
};
case 'merge':
if (!hasImage() || state.images.length < 2) {
if (state.images.length < 2) {
return {
title: '合并图片',
content: `<p class="text-sm text-red-500">请先上传至少2张图片</p>`,
actions: `<button onclick="goHome()" class="px-4 py-2 bg-gray-200 rounded-lg">关闭</button>`
};
}
state.mergeImageOrder = state.images.map((img, idx) => ({
index: idx,
name: img.name,
@@ -457,7 +350,7 @@
state.mergeImageOrder.forEach(item => {
state.mergeImageSizes[item.index] = { width: item.width, height: item.height };
});
return {
title: '合并图片',
content: `
@@ -513,9 +406,9 @@
</button>
`
};
case 'split':
if (!hasImage()) {
if (state.images.length === 0) {
return {
title: '分割图片',
content: `<p class="text-sm text-red-500">请先上传图片</p>`,
@@ -544,9 +437,9 @@
`,
actions: `<button onclick="applySplit()" class="px-4 py-2 bg-blue-500 text-white rounded-lg w-full">执行分割</button>`
};
case 'hole':
if (!hasImage()) {
if (state.images.length === 0) {
return {
title: '挖孔填充',
content: `<p class="text-sm text-red-500">请先上传图片</p>`,
@@ -590,9 +483,9 @@
<button onclick="goHome()" class="px-4 py-2 bg-gray-200 rounded-lg w-full">关闭面板</button>
`
};
case 'circle':
if (!hasImage()) {
if (state.images.length === 0) {
return {
title: '圆形切图',
content: `<p class="text-sm text-red-500">请先上传图片</p>`,
@@ -629,7 +522,7 @@
`,
actions: `<button onclick="applyCircleCut()" class="px-4 py-2 bg-blue-500 text-white rounded-lg w-full">执行切图</button>`
};
case 'text':
return {
title: '文字图片',
@@ -676,9 +569,9 @@
`,
actions: `<button onclick="createTextImage()" class="px-4 py-2 bg-blue-500 text-white rounded-lg w-full">生成图片</button>`
};
case 'resize':
if (!hasImage()) {
if (state.images.length === 0) {
return {
title: '调整大小',
content: `<p class="text-sm text-red-500">请先上传图片</p>`,
@@ -707,9 +600,9 @@
`,
actions: `<button onclick="applyResize()" class="px-4 py-2 bg-blue-500 text-white rounded-lg w-full">应用</button>`
};
case 'crop':
if (!hasImage()) {
if (state.images.length === 0) {
return {
title: '裁剪',
content: `<p class="text-sm text-red-500">请先上传图片</p>`,
@@ -746,7 +639,7 @@
<button onclick="applyCrop()" class="px-4 py-2 bg-blue-500 text-white rounded-lg w-full">应用裁剪</button>
`
};
default:
return { title: '配置', content: '', actions: '' };
}
@@ -756,29 +649,29 @@
function initMergePanelContent() {
const orderContainer = document.getElementById('mergeImageOrderPanel');
if (!orderContainer) return;
orderContainer.innerHTML = '';
state.mergeImageOrder.forEach((item, idx) => {
const div = document.createElement('div');
div.className = 'image-order-item';
div.draggable = true;
div.dataset.index = idx;
div.innerHTML = `
<span class="drag-handle"><i class="ri-draggable"></i></span>
<img src="${item.dataUrl}" class="w-10 h-10 object-cover rounded">
<span class="text-xs flex-1 truncate">${item.name}</span>
<span class="text-xs bg-blue-500 text-white rounded px-1">#${idx + 1}</span>
`;
div.addEventListener('dragstart', handleDragStart);
div.addEventListener('dragover', handleDragOver);
div.addEventListener('drop', handleDrop);
div.addEventListener('dragend', handleDragEnd);
orderContainer.appendChild(div);
});
renderMergeSizeList();
}
@@ -797,7 +690,7 @@
const checkbox = document.getElementById('mergeUniformSize');
const uniformSettings = document.getElementById('uniformSizeSettings');
const sizeList = document.getElementById('mergeSizeList');
if (checkbox && checkbox.checked) {
if (uniformSettings) uniformSettings.classList.remove('hidden');
if (sizeList) sizeList.classList.add('hidden');
@@ -812,20 +705,20 @@
function renderMergeSizeList() {
const container = document.getElementById('mergeSizeList');
if (!container) return;
container.innerHTML = '';
state.mergeImageOrder.forEach((item, idx) => {
const originalIndex = item.index;
const size = state.mergeImageSizes[originalIndex] || { width: item.width, height: item.height };
const div = document.createElement('div');
div.className = 'flex items-center gap-1 text-xs py-1';
div.innerHTML = `
<span class="truncate w-20">${item.name}</span>
<input type="number" value="${size.width}"
<input type="number" value="${size.width}"
onchange="state.mergeImageSizes[${originalIndex}].width = parseInt(this.value) || ${item.width}"
class="border rounded px-1 py-0.5 w-14" placeholder="宽">
<input type="number" value="${size.height}"
<input type="number" value="${size.height}"
onchange="state.mergeImageSizes[${originalIndex}].height = parseInt(this.value) || ${item.height}"
class="border rounded px-1 py-0.5 w-14" placeholder="高">
`;
@@ -850,11 +743,11 @@
if (draggedItem !== this) {
const fromIdx = parseInt(draggedItem.dataset.index);
const toIdx = parseInt(this.dataset.index);
const temp = state.mergeImageOrder[fromIdx];
state.mergeImageOrder[fromIdx] = state.mergeImageOrder[toIdx];
state.mergeImageOrder[toIdx] = temp;
initMergePanelContent();
}
}
@@ -979,17 +872,10 @@
updateImageList();
hideEmptyHint();
saveState('加载: ' + name);
// 刷新当前面板
refreshCurrentPanel();
};
img.src = dataUrl;
}
// 加载操作结果(不清空原始图片)
function loadOperationResult(dataUrl, name, operationName) {
showPreviewResult(dataUrl, operationName);
}
function drawCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#ffffff';
@@ -1010,7 +896,7 @@
const list = document.getElementById('imageList');
const items = document.getElementById('imageItems');
document.getElementById('imageCount').textContent = `(${state.images.length}张)`;
if (!hasImage()) { list.classList.add('hidden'); return; }
if (state.images.length === 0) { list.classList.add('hidden'); return; }
list.classList.remove('hidden');
items.innerHTML = '';
state.images.forEach((item, index) => {
@@ -1030,7 +916,7 @@
drawCanvas();
updateImageList();
saveState('移除图片');
if (!hasImage()) showEmptyHint();
if (state.images.length === 0) showEmptyHint();
}
function hideEmptyHint() {
@@ -1056,21 +942,21 @@
function applyMerge() {
if (!document.getElementById('mergeDirection')) return;
const direction = document.getElementById('mergeDirection').value;
const gap = parseInt(document.getElementById('mergeGap')?.value) || 0;
const bgColor = document.getElementById('mergeBgColor')?.value || '#ffffff';
const uniformSize = document.getElementById('mergeUniformSize')?.checked;
const uniformWidth = parseInt(document.getElementById('mergeUniformWidth')?.value) || 0;
const uniformHeight = parseInt(document.getElementById('mergeUniformHeight')?.value) || 0;
let cols = 1, rows = state.mergeImageOrder.length;
if (direction === 'horizontal') { cols = state.mergeImageOrder.length; rows = 1; }
else if (direction === 'grid') {
cols = parseInt(document.getElementById('gridCols')?.value) || 2;
rows = parseInt(document.getElementById('gridRows')?.value) || 2;
}
const getActualSize = (item) => {
if (uniformSize) {
const maxWidth = Math.max(...state.mergeImageOrder.map(i => i.width));
@@ -1080,136 +966,53 @@
const size = state.mergeImageSizes[item.index] || { width: item.width, height: item.height };
return { width: size.width || item.width, height: size.height || item.height };
};
// 计算画布尺寸
let canvasWidth = 0, canvasHeight = 0;
if (uniformSize) {
// 统一尺寸:使用固定单元格大小
let maxWidth = 0, maxHeight = 0;
state.mergeImageOrder.forEach(item => {
const size = getActualSize(item);
maxWidth = Math.max(maxWidth, size.width);
maxHeight = Math.max(maxHeight, size.height);
});
canvasWidth = cols * maxWidth + (cols - 1) * gap;
canvasHeight = rows * maxHeight + (rows - 1) * gap;
} else {
// 不统一尺寸:紧密拼接,累加实际尺寸
if (direction === 'horizontal') {
// 横向:累加宽度,取最大高度
state.mergeImageOrder.forEach(item => {
const size = getActualSize(item);
canvasWidth += size.width + gap;
canvasHeight = Math.max(canvasHeight, size.height);
});
canvasWidth -= gap; // 去掉最后一个多余的gap
} else if (direction === 'vertical') {
// 纵向:累加高度,取最大宽度
state.mergeImageOrder.forEach(item => {
const size = getActualSize(item);
canvasHeight += size.height + gap;
canvasWidth = Math.max(canvasWidth, size.width);
});
canvasHeight -= gap;
} else {
// 网格:每行累加宽度,累加行高度
for (let r = 0; r < rows; r++) {
let rowWidth = 0, rowHeight = 0;
for (let c = 0; c < cols; c++) {
const idx = r * cols + c;
if (idx < state.mergeImageOrder.length) {
const size = getActualSize(state.mergeImageOrder[idx]);
rowWidth += size.width + gap;
rowHeight = Math.max(rowHeight, size.height);
}
}
rowWidth -= gap;
canvasWidth = Math.max(canvasWidth, rowWidth);
canvasHeight += rowHeight + gap;
}
canvasHeight -= gap;
}
}
canvas.width = canvasWidth;
canvas.height = canvasHeight;
// 绘制合并结果到画布(预览)
let maxWidth = 0, maxHeight = 0;
state.mergeImageOrder.forEach(item => {
const size = getActualSize(item);
maxWidth = Math.max(maxWidth, size.width);
maxHeight = Math.max(maxHeight, size.height);
});
canvas.width = cols * maxWidth + (cols - 1) * gap;
canvas.height = rows * maxHeight + (rows - 1) * gap;
ctx.fillStyle = bgColor;
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 绘制图片
let currentX = 0, currentY = 0;
if (uniformSize) {
// 统一尺寸:固定单元格,居中绘制
let maxWidth = 0, maxHeight = 0;
state.mergeImageOrder.forEach(item => {
const size = getActualSize(item);
maxWidth = Math.max(maxWidth, size.width);
maxHeight = Math.max(maxHeight, size.height);
});
state.mergeImageOrder.forEach((orderItem, index) => {
if (index >= cols * rows) return;
const col = index % cols;
const row = Math.floor(index / cols);
const x = col * (maxWidth + gap);
const y = row * (maxHeight + gap);
const size = getActualSize(orderItem);
const offsetX = (maxWidth - size.width) / 2;
const offsetY = (maxHeight - size.height) / 2;
const originalImg = state.images.find(img => img.name === orderItem.name);
if (originalImg) {
ctx.drawImage(originalImg.img, x + offsetX, y + offsetY, size.width, size.height);
}
});
} else {
// 不统一尺寸:紧密拼接,无居中偏移
state.mergeImageOrder.forEach((orderItem, index) => {
const size = getActualSize(orderItem);
const originalImg = state.images.find(img => img.name === orderItem.name);
if (!originalImg) return;
if (direction === 'horizontal') {
ctx.drawImage(originalImg.img, currentX, 0, size.width, size.height);
currentX += size.width + gap;
} else if (direction === 'vertical') {
ctx.drawImage(originalImg.img, 0, currentY, size.width, size.height);
currentY += size.height + gap;
} else {
// 网格模式
const col = index % cols;
const row = Math.floor(index / cols);
if (col === 0) currentX = 0;
ctx.drawImage(originalImg.img, currentX, currentY, size.width, size.height);
currentX += size.width + gap;
if (col === cols - 1 || index === state.mergeImageOrder.length - 1) {
currentY += size.height + gap;
}
}
});
}
// 显示预览效果(不清除原始图片)
state.mergeImageOrder.forEach((orderItem, index) => {
if (index >= cols * rows) return;
const col = index % cols;
const row = Math.floor(index / cols);
const x = col * (maxWidth + gap);
const y = row * (maxHeight + gap);
const size = getActualSize(orderItem);
const offsetX = (maxWidth - size.width) / 2;
const offsetY = (maxHeight - size.height) / 2;
const originalImg = state.images.find(img => img.name === orderItem.name);
if (originalImg) {
ctx.drawImage(originalImg.img, x + offsetX, y + offsetY, size.width, size.height);
}
});
const mergedData = canvas.toDataURL('image/png');
showPreviewResult(mergedData, '合并图片');
state.images = [];
loadImage(mergedData, 'merged');
refreshCurrentPanel();
}
function applySplit() {
const cols = parseInt(document.getElementById('splitCols')?.value) || 2;
const rows = parseInt(document.getElementById('splitRows')?.value) || 2;
const img = state.images[0];
const pieceWidth = img.width / cols;
const pieceHeight = img.height / rows;
const resultsDiv = document.getElementById('splitImages');
resultsDiv.innerHTML = '';
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
const pieceCanvas = document.createElement('canvas');
@@ -1217,13 +1020,13 @@
pieceCanvas.height = pieceHeight;
const pieceCtx = pieceCanvas.getContext('2d');
pieceCtx.drawImage(img.img, c * pieceWidth, r * pieceHeight, pieceWidth, pieceHeight, 0, 0, pieceWidth, pieceHeight);
const dataUrl = pieceCanvas.toDataURL('image/png');
const div = document.createElement('div');
div.className = 'relative';
div.innerHTML = `
<img src="${dataUrl}" class="w-full rounded border">
<button onclick="downloadDataUrl('${dataUrl}', 'split_${r}_${c}.png')"
<button onclick="downloadDataUrl('${dataUrl}', 'split_${r}_${c}.png')"
class="absolute bottom-1 right-1 bg-blue-500 text-white px-1 py-0.5 rounded text-xs">
<i class="ri-download-line"></i>
</button>
@@ -1231,7 +1034,7 @@
resultsDiv.appendChild(div);
}
}
document.getElementById('splitResults').classList.remove('hidden');
refreshCurrentPanel();
saveState(`分割 (${cols}x${rows})`);
@@ -1268,7 +1071,7 @@
const mouseUp = () => {
if (!state.isSelecting) return;
state.isSelecting = false;
if (state.currentTool === 'hole') {
applyHole();
} else if (state.currentTool === 'crop') {
@@ -1277,7 +1080,7 @@
document.getElementById('cropWidth').value = Math.round(Math.abs(state.selection.width));
document.getElementById('cropHeight').value = Math.round(Math.abs(state.selection.height));
}
state.selection = null;
state.currentTool = null;
drawCanvas();
@@ -1292,18 +1095,18 @@
function applyHole() {
if (!document.getElementById('holeShape')) return;
const shape = document.getElementById('holeShape').value;
const fill = document.getElementById('holeFill').value;
const color = document.getElementById('holeColor')?.value || '#ffffff';
const blurRadius = parseInt(document.getElementById('holeBlurRadius')?.value) || 10;
const sel = state.selection;
const x = sel.width < 0 ? sel.x + sel.width : sel.x;
const y = sel.height < 0 ? sel.y + sel.height : sel.y;
const w = Math.abs(sel.width);
const h = Math.abs(sel.height);
if (fill === 'color') {
ctx.fillStyle = color;
if (shape === 'rectangle') ctx.fillRect(x, y, w, h);
@@ -1330,23 +1133,23 @@
function applyCircleCut() {
if (!document.getElementById('circleEdge')) return;
const diameter = document.getElementById('circleDiameter')?.value;
const edge = document.getElementById('circleEdge').value;
const borderColor = document.getElementById('circleBorderColor')?.value || '#3b82f6';
const borderWidth = parseInt(document.getElementById('circleBorderWidth')?.value) || 3;
const img = state.images[0];
const size = diameter ? parseInt(diameter) : Math.min(img.width, img.height);
const circleCanvas = document.createElement('canvas');
circleCanvas.width = size; circleCanvas.height = size;
const circleCtx = circleCanvas.getContext('2d');
circleCtx.beginPath();
circleCtx.arc(size/2, size/2, size/2 - (edge === 'border' ? borderWidth : 0), 0, Math.PI * 2);
circleCtx.closePath();
if (edge === 'smooth') {
const gradient = circleCtx.createRadialGradient(size/2, size/2, size/2 - 10, size/2, size/2, size/2);
gradient.addColorStop(0, 'rgba(255,255,255,1)');
@@ -1354,12 +1157,12 @@
circleCtx.fillStyle = gradient;
circleCtx.fill();
}
circleCtx.clip();
const offsetX = (img.width - size) / 2;
const offsetY = (img.height - size) / 2;
circleCtx.drawImage(img.img, -offsetX, -offsetY);
if (edge === 'border') {
circleCtx.strokeStyle = borderColor;
circleCtx.lineWidth = borderWidth;
@@ -1367,95 +1170,103 @@
circleCtx.arc(size/2, size/2, size/2 - borderWidth/2, 0, Math.PI * 2);
circleCtx.stroke();
}
canvas.width = size; canvas.height = size;
ctx.drawImage(circleCanvas, 0, 0);
const circleData = canvas.toDataURL('image/png');
showPreviewResult(circleData, '圆形切图');
state.images = [];
loadImage(circleData, 'circle');
refreshCurrentPanel();
}
function createTextImage() {
if (!document.getElementById('textContent')) return;
const content = document.getElementById('textContent').value;
if (!content.trim()) { alert('请输入文字'); return; }
const font = document.getElementById('textFont').value;
const size = parseInt(document.getElementById('textSize')?.value) || 48;
const color = document.getElementById('textColor')?.value || '#000000';
const transparentBg = document.getElementById('textTransparentBg')?.checked;
const bgColor = document.getElementById('textBgColor')?.value || '#ffffff';
const fontStyle = (state.textStyles.bold ? 'bold ' : '') + (state.textStyles.italic ? 'italic ' : '') + size + 'px ' + font;
const tempCanvas = document.createElement('canvas');
const tempCtx = tempCanvas.getContext('2d');
tempCtx.font = fontStyle;
const lines = content.split('\n');
let maxWidth = 0;
lines.forEach(line => maxWidth = Math.max(maxWidth, tempCtx.measureText(line).width));
const padding = 20;
const lineHeight = size * 1.2;
const totalHeight = lines.length * lineHeight + padding * 2;
const totalWidth = maxWidth + padding * 2;
canvas.width = totalWidth; canvas.height = totalHeight;
if (!transparentBg) {
ctx.fillStyle = bgColor;
ctx.fillRect(0, 0, totalWidth, totalHeight);
} else {
ctx.clearRect(0, 0, totalWidth, totalHeight);
}
ctx.font = fontStyle;
ctx.fillStyle = color;
ctx.textBaseline = 'top';
ctx.textAlign = 'center';
lines.forEach((line, index) => {
ctx.fillText(line, totalWidth/2, padding + index * lineHeight);
});
const textData = canvas.toDataURL('image/png');
showPreviewResult(textData, '文字图片');
state.images = [];
loadImage(textData, 'text');
refreshCurrentPanel();
}
function applyResize() {
if (!document.getElementById('newWidth')) return;
const newWidth = parseInt(document.getElementById('newWidth').value);
const newHeight = parseInt(document.getElementById('newHeight').value);
if (!newWidth || !newHeight) { alert('请输入有效尺寸'); return; }
const img = state.images[0];
canvas.width = newWidth; canvas.height = newHeight;
ctx.drawImage(img.img, 0, 0, newWidth, newHeight);
const resizedData = canvas.toDataURL('image/png');
showPreviewResult(resizedData, '调整大小');
state.images = [];
loadImage(resizedData, 'resized');
refreshCurrentPanel();
}
function applyCrop() {
if (!document.getElementById('cropWidth')) return;
const x = parseInt(document.getElementById('cropX').value) || 0;
const y = parseInt(document.getElementById('cropY').value) || 0;
const w = parseInt(document.getElementById('cropWidth').value);
const h = parseInt(document.getElementById('cropHeight').value);
if (!w || !h) { alert('请输入有效尺寸'); return; }
const img = state.images[0];
canvas.width = w; canvas.height = h;
ctx.drawImage(img.img, x, y, w, h, 0, 0, w, h);
const croppedData = canvas.toDataURL('image/png');
showPreviewResult(croppedData, '裁剪');
state.images = [];
loadImage(croppedData, 'cropped');
refreshCurrentPanel();
}
function saveImage() {