ImageViewer.vue
17.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
<template>
<div class="image-viewer">
<!-- 工具栏 -->
<div class="image-toolbar">
<div class="toolbar-left">
<el-button-group>
<el-button size="small" @click="zoomIn" title="放大">
<template #icon>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 1024 1024"
width="16"
height="16"
>
<path
fill="currentColor"
d="M512 128a384 384 0 1 0 384 384A384 384 0 0 0 512 128zm192 416H544v160a32 32 0 0 1-64 0V544H320a32 32 0 0 1 0-64h160V320a32 32 0 0 1 64 0v160h160a32 32 0 0 1 0 64z"
/>
</svg>
</template>
</el-button>
<el-button size="small" @click="zoomOut" title="缩小">
<template #icon>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 1024 1024"
width="16"
height="16"
>
<path
fill="currentColor"
d="M512 128a384 384 0 1 0 384 384A384 384 0 0 0 512 128zm192 416H320a32 32 0 0 1 0-64h384a32 32 0 0 1 0 64z"
/>
</svg>
</template>
</el-button>
<el-button size="small" @click="resetZoom" title="重置缩放">
<template #icon>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 1024 1024"
width="16"
height="16"
>
<path
fill="currentColor"
d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm192 472c0 4.4-3.6 8-8 8H544v152c0 4.4-3.6 8-8 8h-48c-4.4 0-8-3.6-8-8V544H328c-4.4 0-8-3.6-8-8v-48c0-4.4 3.6-8 8-8h152V328c0-4.4 3.6-8 8-8h48c4.4 0 8 3.6 8 8v152h152c4.4 0 8 3.6 8 8v48z"
/>
</svg>
</template>
</el-button>
<el-button size="small" @click="rotateImage" title="旋转">
<template #icon>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 1024 1024"
width="16"
height="16"
>
<path
fill="currentColor"
d="M716.8 290.133333c-110.933333-102.4-281.6-106.666667-396.8-12.8S170.666667 537.6 247.466667 665.6c59.733333 106.666667 179.2 166.4 302.933333 149.333333s221.866667-102.4 256-221.866666c8.533333-34.133333 42.666667-51.2 76.8-42.666667 34.133333 8.533333 51.2 42.666667 42.666667 76.8-68.266667 226.133333-302.933333 354.133333-524.8 290.133333C174.933333 853.333333 42.666667 618.666667 106.666667 392.533333c42.666667-145.066667 153.6-256 298.666666-298.666666s298.666667 0 405.333334 102.4l81.066666-81.066667c8.533333-8.533333 21.333333-12.8 34.133334-8.533333 4.266667 12.8 12.8 21.333333 12.8 34.133333v264.533333c0 17.066667-12.8 29.866667-29.866667 29.866667h-260.266667c-12.8 0-25.6-8.533333-29.866666-17.066667s0-25.6 8.533333-34.133333l89.6-93.866667zM512 601.6c-46.933333 0-85.333333-38.4-85.333333-89.6s38.4-89.6 85.333333-89.6 85.333333 38.4 85.333333 89.6-38.4 89.6-85.333333 89.6z"
/>
</svg>
</template>
</el-button>
</el-button-group>
<span class="zoom-info">{{ Math.round(zoom * 100) }}%</span>
</div>
<!-- 隐藏文件名显示 -->
<!-- <div class="file-info">
{{ fileName }}
</div> -->
<div class="toolbar-right">
<el-button size="small" @click="downloadImage">
<template #icon>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 1024 1024"
width="16"
height="16"
>
<path
fill="currentColor"
d="M505.7 661a8 8 0 0 0 12.6 0l112-141.7c4.1-5.2.4-12.9-6.3-12.9h-74.1V168c0-4.4-3.6-8-8-8h-60c-4.4 0-8 3.6-8 8v338.3H400c-6.7 0-10.4 7.7-6.3 12.9l112 141.8zM878 626h-60c-4.4 0-8 3.6-8 8v154H214V634c0-4.4-3.6-8-8-8h-60c-4.4 0-8 3.6-8 8v198c0 17.7 14.3 32 32 32h684c17.7 0 32-14.3 32-32V634c0-4.4-3.6-8-8-8z"
/>
</svg>
</template>
下载
</el-button>
</div>
</div>
<!-- 图片容器 -->
<div
class="image-container"
ref="imageContainerRef"
@wheel.prevent="handleWheel"
@mousedown="startDrag"
@mousemove="onDrag"
@mouseup="endDrag"
@mouseleave="endDrag"
>
<div v-if="loading" class="loading-state">
<el-skeleton :rows="10" animated />
</div>
<div v-else-if="error" class="error-state">
<i class="fas fa-exclamation-triangle"></i>
<p class="error-text">{{ error }}</p>
<el-button @click="loadImage" size="small">重试</el-button>
</div>
<img
v-else
:src="imageUrl"
:alt="fileName"
:style="{
transform: `scale(${zoom}) rotate(${rotation}deg)`,
transformOrigin: 'center center',
left: `${translateX}px`,
top: `${translateY}px`,
}"
class="image-content"
@load="handleImageLoad"
@error="handleImageError"
@dragstart="handleDragStart"
draggable="true"
/>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch } from "vue";
import { ElButton, ElButtonGroup, ElSkeleton, ElMessage } from "element-plus";
import { downloadFile } from "@/api/files";
import { fileCache } from "@/utils/fileCache";
interface Props {
fileId: string | number;
fileName: string;
isChatAnswer?: boolean;
}
interface Emits {
(e: "mounted"): void;
}
const props = withDefaults(defineProps<Props>(), {
isChatAnswer: false,
});
const emit = defineEmits<Emits>();
const loading = ref(true);
const error = ref<string | null>(null);
const imageUrl = ref("");
const zoom = ref(1);
const rotation = ref(0);
const translateX = ref(0);
const translateY = ref(0);
const isDragging = ref(false);
const dragStartX = ref(0);
const dragStartY = ref(0);
const imageContainerRef = ref<HTMLDivElement | null>(null);
// 加载图片
const loadImage = async () => {
try {
loading.value = true;
error.value = null;
const fileId = props.fileId;
// 1. 尝试从持久化缓存读取
try {
const cached = await fileCache.getFile(fileId);
if (cached && (cached.content instanceof Blob)) {
console.log("图片命中持久化缓存:", fileId);
imageUrl.value = URL.createObjectURL(cached.content);
loading.value = false;
return;
}
} catch (e) {
console.warn("读取图片持久化缓存失败:", e);
}
console.log("开始下载图片,fileId:", props.fileId, "isChatAnswer:", props.isChatAnswer);
// 使用 API 下载图片
let response;
if (props.isChatAnswer) {
try {
const cached = await fileCache.getFile(props.fileId);
if (cached && cached.content instanceof Blob) {
response = cached.content;
} else {
response = await downloadFile(props.fileId);
}
} catch (error) {
response = await downloadFile(props.fileId);
}
} else {
response = await downloadFile(props.fileId);
}
console.log("图片下载响应:", response);
// 检查响应类型
let blob: Blob;
if (response instanceof Blob) {
blob = response;
} else if ((response as any).data instanceof Blob) {
blob = (response as any).data;
} else if (props.isChatAnswer && (response as any).data?.content) {
// 智能体回答文件可能是 Base64 或 Markdown
const content = (response as any).data.content;
if (content.startsWith("data:image")) {
const parts = content.split(",");
const byteString = atob(parts[1]);
const mimeString = parts[0].split(":")[1].split(";")[0];
const ab = new ArrayBuffer(byteString.length);
const ia = new Uint8Array(ab);
for (let i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
blob = new Blob([ab], { type: mimeString });
} else {
blob = new Blob([content], { type: "image/png" }); // 降级处理
}
} else {
throw new Error(
`下载的数据不是有效的Blob格式,实际类型: ${typeof response}`,
);
}
console.log("Blob类型:", typeof blob, "是否为Blob:", blob instanceof Blob);
// 检查 Blob 大小
if (blob.size === 0) {
throw new Error("下载的图片文件为空");
}
console.log("Blob大小:", blob.size, "字节");
console.log("Blob详细信息:", {
type: blob.type,
size: blob.size,
isImage: blob.type.startsWith("image/"),
});
// 如果 Blob 没有正确的 MIME 类型,尝试根据文件名推断
let finalBlob = blob;
if (!blob.type || !blob.type.startsWith("image/")) {
console.log("Blob MIME类型不正确,尝试根据文件名推断类型");
const fileName = props.fileName.toLowerCase();
let mimeType = "image/jpeg"; // 默认类型
// 根据文件扩展名推断 MIME 类型
if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
mimeType = "image/jpeg";
} else if (fileName.endsWith(".png")) {
mimeType = "image/png";
} else if (fileName.endsWith(".gif")) {
mimeType = "image/gif";
} else if (fileName.endsWith(".webp")) {
mimeType = "image/webp";
} else if (fileName.endsWith(".svg")) {
mimeType = "image/svg+xml";
} else if (fileName.endsWith(".bmp")) {
mimeType = "image/bmp";
} else if (fileName.endsWith(".ico")) {
mimeType = "image/x-icon";
} else if (fileName.endsWith(".tiff") || fileName.endsWith(".tif")) {
mimeType = "image/tiff";
}
console.log("推断的MIME类型:", mimeType);
finalBlob = new Blob([blob], { type: mimeType });
}
// 2. 写入持久化缓存
await fileCache.setFile({
fileId,
content: finalBlob,
type: "image",
fileName: props.fileName || "image",
});
// 将 Blob 转换为 URL
imageUrl.value = window.URL.createObjectURL(finalBlob);
console.log("图片URL创建成功:", imageUrl.value);
loading.value = false;
} catch (err: any) {
console.error("加载图片失败:", err);
error.value = `图片加载失败: ${err.message || "未知错误"}`;
loading.value = false;
}
};
// 图片加载成功
const handleImageLoad = (event: Event) => {
const target = event.target as HTMLImageElement;
console.log("图片在DOM中加载完成", {
naturalWidth: target.naturalWidth,
naturalHeight: target.naturalHeight,
complete: target.complete,
src: target.src,
});
};
// 图片加载失败
const handleImageError = (event: Event) => {
const target = event.target as HTMLImageElement;
error.value = "图片格式不支持或已损坏";
console.error("图片在DOM中加载失败", {
error: event,
src: target.src,
currentSrc: target.currentSrc,
});
};
// 处理拖拽开始
const handleDragStart = (event: DragEvent) => {
try {
const payload = {
from: "ImageViewer",
type: "file",
files: [
{
id: props.fileId,
name: props.fileName,
type: "image",
isChatAnswer: props.isChatAnswer,
},
],
};
const jsonStr = JSON.stringify(payload);
event.dataTransfer!.setData("application/json", jsonStr);
event.dataTransfer!.setData("text/plain", jsonStr);
event.dataTransfer!.effectAllowed = "copyMove";
console.log("📸 ImageViewer 拖拽开始:", payload);
} catch (e) {
console.error("❌ ImageViewer 设置拖拽数据失败:", e);
}
};
// 放大
const zoomIn = () => {
zoom.value = Math.min(5, zoom.value + 0.2);
};
// 缩小
const zoomOut = () => {
zoom.value = Math.max(0.2, zoom.value - 0.2);
};
// 重置缩放
const resetZoom = () => {
zoom.value = 1;
rotation.value = 0;
translateX.value = 0;
translateY.value = 0;
};
// 旋转
const rotateImage = () => {
rotation.value = (rotation.value + 90) % 360;
};
// 鼠标滚轮缩放
const handleWheel = (event: WheelEvent) => {
if (event.deltaY < 0) {
zoomIn();
} else {
zoomOut();
}
};
// 开始拖拽
const startDrag = (event: MouseEvent) => {
isDragging.value = true;
dragStartX.value = event.clientX - translateX.value;
dragStartY.value = event.clientY - translateY.value;
};
// 拖拽中
const onDrag = (event: MouseEvent) => {
if (!isDragging.value) return;
translateX.value = event.clientX - dragStartX.value;
translateY.value = event.clientY - dragStartY.value;
};
// 结束拖拽
const endDrag = () => {
isDragging.value = false;
};
// 下载图片
const downloadImage = async () => {
try {
// 下载图片
let response;
if (props.isChatAnswer) {
try {
const cached = await fileCache.getFile(props.fileId);
if (cached && cached.content instanceof Blob) {
response = cached.content;
} else {
response = await downloadFile(props.fileId);
}
} catch (error) {
response = await downloadFile(props.fileId);
}
} else {
response = await downloadFile(props.fileId);
}
console.log("下载图片响应:", response);
// 获取 Blob
let blob: Blob;
if (response instanceof Blob) {
blob = response;
} else if ((response as any).data instanceof Blob) {
blob = (response as any).data;
} else if (props.isChatAnswer && (response as any).data?.content) {
const content = (response as any).data.content;
if (content.startsWith("data:image")) {
const parts = content.split(",");
const byteString = atob(parts[1]);
const mimeString = parts[0].split(":")[1].split(";")[0];
const ab = new ArrayBuffer(byteString.length);
const ia = new Uint8Array(ab);
for (let i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
blob = new Blob([ab], { type: mimeString });
} else {
blob = new Blob([content], { type: "image/png" });
}
} else {
throw new Error(
`下载的数据不是有效的Blob格式,实际类型: ${typeof response}`,
);
}
// 创建下载链接
const url = window.URL.createObjectURL(blob);
console.log("下载URL创建成功:", url);
const a = document.createElement("a");
a.href = url;
a.download = props.fileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
ElMessage.success("图片下载成功");
} catch (err: any) {
console.error("下载图片失败:", err);
ElMessage.error(`图片下载失败: ${err.message || "未知错误"}`);
}
};
// 监听 fileId 变化,重新加载图片
watch(
() => props.fileId,
(newFileId, oldFileId) => {
if (newFileId !== oldFileId) {
console.log("📸 检测到 fileId 变化,重新加载图片:", {
oldFileId,
newFileId,
});
// 清理旧的 Blob URL
if (imageUrl.value && imageUrl.value.startsWith("blob:")) {
window.URL.revokeObjectURL(imageUrl.value);
imageUrl.value = "";
}
// 重置状态
zoom.value = 1;
rotation.value = 0;
translateX.value = 0;
translateY.value = 0;
// 重新加载图片
loadImage();
}
},
);
onMounted(() => {
loadImage();
emit("mounted");
});
onBeforeUnmount(() => {
// 清理创建的 Blob URL,避免内存泄漏
if (imageUrl.value && imageUrl.value.startsWith("blob:")) {
window.URL.revokeObjectURL(imageUrl.value);
}
});
</script>
<style scoped lang="scss">
.image-viewer {
display: flex;
flex-direction: column;
height: 100%;
width: 100%;
background-color: var(--color-bg, #141518);
color: var(--color-text, #eee);
overflow: hidden;
.image-toolbar {
padding: 8px 16px;
display: flex;
justify-content: space-between;
align-items: center;
background-color: var(--color-card, #232324);
border-bottom: 1px solid var(--color-border, #333);
flex-shrink: 0;
.toolbar-left {
display: flex;
align-items: center;
gap: 12px;
.zoom-info {
font-size: 14px;
color: var(--color-text-secondary, #999);
min-width: 45px;
text-align: center;
}
}
.file-info {
font-size: 14px;
color: var(--color-text-secondary, #999);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 300px;
text-align: center;
flex: 1;
margin: 0 16px;
}
.toolbar-right {
display: flex;
align-items: center;
}
}
.image-container {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
position: relative;
background-color: var(--color-tertiary, #23232a);
.loading-state,
.error-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 16px;
color: var(--color-text-secondary);
padding: 20px;
width: 100%;
max-width: 600px;
i {
font-size: 48px;
}
span,
.error-text {
font-size: 14px;
margin: 0;
}
}
.error-state {
i {
color: #f56c6c;
}
}
.image-content {
position: relative;
max-width: 100%;
max-height: 100%;
width: auto;
height: auto;
transition: transform 0.2s ease;
object-fit: contain;
cursor: move;
display: block;
}
}
}
</style>