From 4bc7ddf08eb5638978f124a96da0f50eaa786d9b Mon Sep 17 00:00:00 2001 From: xiaowang <2161656029@qq.com> Date: Sun, 8 Nov 2026 19:37:45 +0800 Subject: [PATCH] =?UTF-8?q?=E7=AE=A1=E7=90=86=E7=AB=AF=E5=AE=9E=E5=86=B5?= =?UTF-8?q?=E7=85=A7=E7=89=87=E4=B8=8A=E4=BC=A0=EF=BC=9A=E6=8C=89=E9=9C=80?= =?UTF-8?q?=E5=8A=A0=E8=BD=BD=20heic2any=20=E5=B0=86=20HEIC/HEIF=20?= =?UTF-8?q?=E8=BD=AC=20JPEG=20=E5=90=8E=E6=B2=BF=E7=94=A8=E5=8E=9F?= =?UTF-8?q?=E6=9C=89=E4=B8=8A=E4=BC=A0=E9=93=BE=E8=B7=AF=EF=BC=8C=E4=BA=8C?= =?UTF-8?q?=E7=BB=B4=E7=A0=81=E7=BB=A7=E7=BB=AD=E6=8E=92=E9=99=A4=20HEIC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- JC-Salon-Frontend/package-lock.json | 7 ++ JC-Salon-Frontend/package.json | 1 + .../src/utils/heic-image.test.ts | 75 +++++++++++++++++++ JC-Salon-Frontend/src/utils/heic-image.ts | 74 ++++++++++++++++++ .../src/views/admin/AnnouncementsView.vue | 6 +- .../src/views/admin/ShopsView.vue | 12 ++- .../src/views/admin/SystemMessagesView.vue | 6 +- .../src/views/admin/UsersView.vue | 3 +- JC-Salon-Frontend/vite.config.ts | 3 + 9 files changed, 178 insertions(+), 9 deletions(-) create mode 100644 JC-Salon-Frontend/src/utils/heic-image.test.ts create mode 100644 JC-Salon-Frontend/src/utils/heic-image.ts diff --git a/JC-Salon-Frontend/package-lock.json b/JC-Salon-Frontend/package-lock.json index 8f0cf12a..4f3eed53 100644 --- a/JC-Salon-Frontend/package-lock.json +++ b/JC-Salon-Frontend/package-lock.json @@ -13,6 +13,7 @@ "ant-design-vue": "^4.2.6", "axios": "^1.13.5", "element-plus": "^2.13.2", + "heic2any": "^0.0.4", "pinia": "^3.0.4", "vue": "^3.5.25", "vue-router": "^4.6.4" @@ -2693,6 +2694,12 @@ "node": ">= 0.4" } }, + "node_modules/heic2any": { + "version": "0.0.4", + "resolved": "https://registry.npmjs.org/heic2any/-/heic2any-0.0.4.tgz", + "integrity": "sha512-3lLnZiDELfabVH87htnRolZ2iehX9zwpRyGNz22GKXIu0fznlblf0/ftppXKNqS26dqFSeqfIBhAmAj/uSp0cA==", + "license": "MIT" + }, "node_modules/hookable": { "version": "5.5.3", "resolved": "https://registry.npmmirror.com/hookable/-/hookable-5.5.3.tgz", diff --git a/JC-Salon-Frontend/package.json b/JC-Salon-Frontend/package.json index bbcfa3d7..753af3ad 100644 --- a/JC-Salon-Frontend/package.json +++ b/JC-Salon-Frontend/package.json @@ -15,6 +15,7 @@ "ant-design-vue": "^4.2.6", "axios": "^1.13.5", "element-plus": "^2.13.2", + "heic2any": "^0.0.4", "pinia": "^3.0.4", "vue": "^3.5.25", "vue-router": "^4.6.4" diff --git a/JC-Salon-Frontend/src/utils/heic-image.test.ts b/JC-Salon-Frontend/src/utils/heic-image.test.ts new file mode 100644 index 00000000..d59afe34 --- /dev/null +++ b/JC-Salon-Frontend/src/utils/heic-image.test.ts @@ -0,0 +1,75 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const convertMock = vi.hoisted(() => vi.fn()) + +vi.mock('heic2any', () => ({ + default: convertMock +})) + +import { + convertHeicToJpegFile, + HEIC_CONVERT_FAILED_MESSAGE, + HEIC_CONVERT_TOO_LARGE_MESSAGE, + isHeicFile +} from './heic-image' + +const FIVE_MB = 5 * 1024 * 1024 + +const createHeicFile = (name = 'live.heic', type = 'image/heic') => new File( + [new Uint8Array(8)], + name, + { type, lastModified: 1 } +) + +describe('heic-image', () => { + beforeEach(() => { + convertMock.mockReset() + }) + + it('识别 HEIC/HEIF 的 MIME 与扩展名', () => { + expect(isHeicFile(createHeicFile('a.heic', 'image/heic'))).toBe(true) + expect(isHeicFile(createHeicFile('a.heif', 'image/heif'))).toBe(true) + expect(isHeicFile(createHeicFile('a.HEIC', ''))).toBe(true) + expect(isHeicFile(createHeicFile('a.heif', ''))).toBe(true) + expect(isHeicFile(createHeicFile('a.jpg', 'image/jpeg'))).toBe(false) + expect(isHeicFile(createHeicFile('a.png', 'image/png'))).toBe(false) + }) + + it('非 HEIC 文件原样返回且不加载转换库', async () => { + const file = createHeicFile('photo.jpg', 'image/jpeg') + + await expect(convertHeicToJpegFile(file)).resolves.toBe(file) + expect(convertMock).not.toHaveBeenCalled() + }) + + it('HEIC 转换成功时输出 JPEG File', async () => { + convertMock.mockResolvedValue(new Blob([new Uint8Array(4)], { type: 'image/jpeg' })) + const file = createHeicFile('live.heic', 'image/heic') + + const converted = await convertHeicToJpegFile(file) + + expect(converted.name).toBe('live.jpg') + expect(converted.type).toBe('image/jpeg') + expect(converted.size).toBe(4) + expect(converted.lastModified).toBe(1) + expect(convertMock).toHaveBeenCalledWith({ blob: file, toType: 'image/jpeg', quality: 0.92 }) + }) + + it('转换失败时抛出明确提示', async () => { + convertMock.mockRejectedValue(new Error('decode failed')) + + await expect(convertHeicToJpegFile(createHeicFile())).rejects.toThrow(HEIC_CONVERT_FAILED_MESSAGE) + }) + + it('转换结果为空时抛出明确提示', async () => { + convertMock.mockResolvedValue(new Blob([])) + + await expect(convertHeicToJpegFile(createHeicFile())).rejects.toThrow(HEIC_CONVERT_FAILED_MESSAGE) + }) + + it('转换后超过 5MB 时抛出超限提示', async () => { + convertMock.mockResolvedValue(new Blob([new Uint8Array(FIVE_MB + 1)])) + + await expect(convertHeicToJpegFile(createHeicFile())).rejects.toThrow(HEIC_CONVERT_TOO_LARGE_MESSAGE) + }) +}) diff --git a/JC-Salon-Frontend/src/utils/heic-image.ts b/JC-Salon-Frontend/src/utils/heic-image.ts new file mode 100644 index 00000000..42c9d183 --- /dev/null +++ b/JC-Salon-Frontend/src/utils/heic-image.ts @@ -0,0 +1,74 @@ +import { MAX_IMAGE_UPLOAD_SIZE } from '@/utils/image-upload' + +const HEIC_EXTENSIONS = ['.heic', '.heif'] +const HEIC_MIME_TYPES = new Set(['image/heic', 'image/heif', 'image/heic-sequence', 'image/heif-sequence']) + +export const HEIC_CONVERT_FAILED_MESSAGE = '该图片格式无法转换,请导出为 JPG 后再上传' +export const HEIC_CONVERT_TOO_LARGE_MESSAGE = '转换后的图片超过 5MB 上限,请压缩后重试' + +type HeicConverter = (options: { + blob: Blob + toType?: string + quality?: number + multiple?: boolean + gifInterval?: number +}) => Promise + +/** 识别 HEIC/HEIF:优先看 MIME,部分系统给不到 MIME 时按扩展名兜底。 */ +export const isHeicFile = (file: File) => { + const type = (file.type || '').toLowerCase() + if (HEIC_MIME_TYPES.has(type)) { + return true + } + const name = (file.name || '').toLowerCase().split(/[?#]/)[0] || '' + return HEIC_EXTENSIONS.some(extension => name.endsWith(extension)) +} + +const buildJpegFileName = (fileName: string) => { + const dotIndex = fileName.lastIndexOf('.') + const baseName = dotIndex > -1 ? fileName.slice(0, dotIndex) : fileName + return `${baseName || 'image'}.jpg` +} + +/** 按需加载 libheif WASM 转换库,只有真正选择 HEIC/HEIF 时才进入首屏之外的异步 chunk。 */ +const loadHeicConverter = async () => { + const heic2anyModule = await import('heic2any') + return (heic2anyModule as unknown as { default: HeicConverter }).default +} + +/** + * 把 HEIC/HEIF 静态帧转成 JPEG 的 File,非 HEIC/HEIF 原样返回。 + * 转换失败或转换后超过 5MB 上限时抛出带明确提示的 Error,调用方不得继续上传。 + */ +export const convertHeicToJpegFile = async ( + file: File, + maxSize = MAX_IMAGE_UPLOAD_SIZE +): Promise => { + if (!isHeicFile(file)) { + return file + } + + let convertedBlob: Blob | null = null + try { + const convert = await loadHeicConverter() + const result = await convert({ blob: file, toType: 'image/jpeg', quality: 0.92 }) + convertedBlob = Array.isArray(result) ? result[0] ?? null : result + } catch { + throw new Error(HEIC_CONVERT_FAILED_MESSAGE) + } + + if (!convertedBlob || convertedBlob.size === 0) { + throw new Error(HEIC_CONVERT_FAILED_MESSAGE) + } + + const convertedFile = new File([convertedBlob], buildJpegFileName(file.name), { + type: 'image/jpeg', + lastModified: file.lastModified + }) + + if (convertedFile.size > maxSize) { + throw new Error(HEIC_CONVERT_TOO_LARGE_MESSAGE) + } + + return convertedFile +} diff --git a/JC-Salon-Frontend/src/views/admin/AnnouncementsView.vue b/JC-Salon-Frontend/src/views/admin/AnnouncementsView.vue index 85810baf..95514641 100644 --- a/JC-Salon-Frontend/src/views/admin/AnnouncementsView.vue +++ b/JC-Salon-Frontend/src/views/admin/AnnouncementsView.vue @@ -41,7 +41,7 @@ - + 添加图片 @@ -79,6 +79,7 @@ import { message, Modal } from 'ant-design-vue' */ import { adminAnnouncementApi, adminFileApi, type AnnouncementVO, type MessageTargetOptionsVO } from '@/api/admin' import { extractRichText, renderRichContent } from '@/utils/rich-content' +import { convertHeicToJpegFile } from '@/utils/heic-image' /** loading is a reactive state variable used by the template and event handlers. */ const loading = ref(false) @@ -160,7 +161,8 @@ const openCreate = () => { const uploadAnnouncementImage = async (file: File) => { imageUploading.value = true try { - const uploaded = await adminFileApi.uploadFile(file) + const uploadCandidate = await convertHeicToJpegFile(file) + const uploaded = await adminFileApi.uploadFile(uploadCandidate) if (uploaded?.id) form.imageFileIds.push(uploaded.id) message.success('图片已上传,提交后会进入审核') } catch (error) { diff --git a/JC-Salon-Frontend/src/views/admin/ShopsView.vue b/JC-Salon-Frontend/src/views/admin/ShopsView.vue index 9e8865cb..7ae37ea2 100644 --- a/JC-Salon-Frontend/src/views/admin/ShopsView.vue +++ b/JC-Salon-Frontend/src/views/admin/ShopsView.vue @@ -292,7 +292,7 @@
首页轮播图,建议尺寸 750x300 像素
店铺详情展示图 { /** beforeUpload is a local helper used by this page script. */ const beforeUpload = (file: File) => { - const isImage = file.type.startsWith('image/') + const isImage = file.type.startsWith('image/') || isHeicFile(file) if (!isImage) { message.error('只能上传图片文件') } @@ -1781,6 +1782,7 @@ const handleUploadBanner: UploadProps['customRequest'] = async (options) => { file: uploadFile, scene: 'admin-shop-banner', concurrency: 3, + preprocessFile: convertHeicToJpegFile, api: { initUpload: adminFileApi.initChunkUpload, uploadChunk: adminFileApi.uploadChunk, @@ -1862,6 +1864,7 @@ const handleUploadImage: UploadProps['customRequest'] = async (options) => { file: uploadFile, scene: 'admin-shop-image', concurrency: 3, + preprocessFile: convertHeicToJpegFile, api: { initUpload: adminFileApi.initChunkUpload, uploadChunk: adminFileApi.uploadChunk, @@ -1943,6 +1946,7 @@ const handleUploadThemeBackground: UploadProps['customRequest'] = async (options file: uploadFile, scene: 'admin-shop-theme-background', concurrency: 3, + preprocessFile: convertHeicToJpegFile, api: { initUpload: adminFileApi.initChunkUpload, uploadChunk: adminFileApi.uploadChunk, diff --git a/JC-Salon-Frontend/src/views/admin/SystemMessagesView.vue b/JC-Salon-Frontend/src/views/admin/SystemMessagesView.vue index b7b2dd9e..27fcf526 100644 --- a/JC-Salon-Frontend/src/views/admin/SystemMessagesView.vue +++ b/JC-Salon-Frontend/src/views/admin/SystemMessagesView.vue @@ -26,7 +26,7 @@
- +
上传图片 @@ -170,6 +170,7 @@ import SystemMessageCard from '@/components/SystemMessageCard.vue' */ import { adminFileApi, adminSystemMessageApi, type SystemMessageCreateRequest, type SystemMessageVO } from '@/api/admin' import { createChunkUploadTask } from '@/utils/chunk-upload' +import { convertHeicToJpegFile, isHeicFile } from '@/utils/heic-image' import type { IdType } from '@/utils/id' /** @@ -391,7 +392,7 @@ const resetForm = () => { */ const handleImageUpload = async (options: any) => { const file = options.file as File - if (!file?.type?.startsWith('image/')) { + if (!file?.type?.startsWith('image/') && !isHeicFile(file)) { message.warning('请上传图片文件') options.onError?.(new Error('invalid image')) return @@ -402,6 +403,7 @@ const handleImageUpload = async (options: any) => { file, scene: 'admin-system-message-image', concurrency: 3, + preprocessFile: convertHeicToJpegFile, api: { initUpload: adminFileApi.initChunkUpload, uploadChunk: adminFileApi.uploadChunk, diff --git a/JC-Salon-Frontend/src/views/admin/UsersView.vue b/JC-Salon-Frontend/src/views/admin/UsersView.vue index d5733ab4..6c522593 100644 --- a/JC-Salon-Frontend/src/views/admin/UsersView.vue +++ b/JC-Salon-Frontend/src/views/admin/UsersView.vue @@ -359,6 +359,7 @@ import { sameId } from '@/utils/id' import { usePermission } from '@/utils/permission' import { runWithGlobalLoading } from '@/utils/action-loading' import { createChunkUploadTask } from '@/utils/chunk-upload' +import { isHeicFile } from '@/utils/heic-image' import { useAdminViewport } from '@/composables/useAdminViewport' import AdminMobileCardList from '@/components/admin/AdminMobileCardList.vue' import AdminMobileFab from '@/components/admin/AdminMobileFab.vue' @@ -658,7 +659,7 @@ const handlePhoneFocus = () => { /** beforeUploadWechatQr validates QR image files before upload. */ const beforeUploadWechatQr = (file: File) => { - const isImage = file.type.startsWith('image/') && file.type !== 'image/gif' + const isImage = file.type.startsWith('image/') && file.type !== 'image/gif' && !isHeicFile(file) if (!isImage) { message.error('二维码仅支持 JPG、PNG 或 WebP 图片') } diff --git a/JC-Salon-Frontend/vite.config.ts b/JC-Salon-Frontend/vite.config.ts index b439431f..bf60a108 100644 --- a/JC-Salon-Frontend/vite.config.ts +++ b/JC-Salon-Frontend/vite.config.ts @@ -68,6 +68,9 @@ export default defineConfig(({ mode }) => { return undefined } const normalizedId = id.replaceAll('\\', '/') + if (normalizedId.includes('heic2any')) { + return 'heic2any' + } if (normalizedId.includes('@ant-design/icons-vue')) { return 'antdv-icons' }