This commit is contained in:
2025-10-09 10:02:37 +08:00
parent 4065da3766
commit db67a99288
7 changed files with 247 additions and 16 deletions

View File

@@ -0,0 +1,78 @@
/**
* 通过后端代理获取图片并转换为Base64
* @param imageUrl 原始图片URL
* @param maxSize 最大尺寸默认80px
* @returns Promise<string | null> Base64字符串或null
*/
export async function convertImageToBase64ViaProxy(imageUrl: string, maxSize: number = 80): Promise<string | null> {
if (!imageUrl) return null
try {
const proxyUrl = `http://127.0.0.1:8081/api/proxy/image-url?url=${encodeURIComponent(imageUrl)}`
const response = await fetch(proxyUrl)
if (!response.ok) return null
const contentType = response.headers.get('Content-Type')
const arrayBuffer = await response.arrayBuffer()
if (!arrayBuffer || arrayBuffer.byteLength === 0) return null
if (arrayBuffer.byteLength < 1000) return null
const mimeType = contentType && contentType.startsWith('image/') ? contentType : 'image/jpeg'
const imageBlob = new Blob([arrayBuffer], { type: mimeType })
const objectUrl = URL.createObjectURL(imageBlob)
return new Promise((resolve) => {
const img = new Image()
img.onload = () => {
try {
const canvas = document.createElement('canvas')
const ratio = Math.min(maxSize / img.width, maxSize / img.height)
canvas.width = img.width * ratio
canvas.height = img.height * ratio
const ctx = canvas.getContext('2d')
if (!ctx) {
URL.revokeObjectURL(objectUrl)
resolve(null)
return
}
ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
const base64 = canvas.toDataURL('image/jpeg', 0.8)
URL.revokeObjectURL(objectUrl)
resolve(base64)
} catch (error) {
URL.revokeObjectURL(objectUrl)
resolve(null)
}
}
img.onerror = () => {
URL.revokeObjectURL(objectUrl)
resolve(null)
}
img.src = objectUrl
})
} catch (error) {
return null
}
}
/**
* 批量处理图片转换
* @param imageUrls 图片URL数组
* @param maxSize 最大尺寸
* @returns Promise<(string | null)[]> Base64数组
*/
export async function batchConvertImages(imageUrls: string[], maxSize: number = 80): Promise<(string | null)[]> {
const promises = imageUrls.map(async (url) => {
if (!url) return null
return await convertImageToBase64ViaProxy(url, maxSize)
})
return await Promise.all(promises)
}