feat avatar compress uploads to 20kb

This commit is contained in:
IanShaw027
2026-04-21 08:53:59 +08:00
parent 07f23aaa7d
commit 6da08262d7
8 changed files with 321 additions and 44 deletions

View File

@@ -176,6 +176,9 @@ const authStore = useAuthStore()
const appStore = useAppStore()
const maxAvatarBytes = 100 * 1024
const targetAvatarUploadBytes = 20 * 1024
const avatarScaleSteps = [1, 0.92, 0.84, 0.76, 0.68, 0.6, 0.52, 0.44, 0.36]
const avatarQualitySteps = [0.92, 0.84, 0.76, 0.68, 0.6, 0.52, 0.44, 0.36]
const avatarDraft = ref(props.user?.avatar_url?.trim() || '')
const avatarSaving = ref(false)
@@ -341,6 +344,72 @@ function readFileAsDataURL(file: File): Promise<string> {
})
}
function loadImage(dataURL: string): Promise<HTMLImageElement> {
return new Promise((resolve, reject) => {
const image = new Image()
image.onload = () => resolve(image)
image.onerror = () => reject(new Error(t('profile.avatar.readFailed')))
image.src = dataURL
})
}
function canvasToBlob(canvas: HTMLCanvasElement, type: string, quality: number): Promise<Blob> {
return new Promise((resolve, reject) => {
canvas.toBlob((blob) => {
if (!blob) {
reject(new Error(t('profile.avatar.compressFailed')))
return
}
resolve(blob)
}, type, quality)
})
}
async function compressAvatarFile(file: File): Promise<File> {
const sourceDataURL = await readFileAsDataURL(file)
const image = await loadImage(sourceDataURL)
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
if (!ctx) {
throw new Error(t('profile.avatar.compressFailed'))
}
for (const scale of avatarScaleSteps) {
const width = Math.max(1, Math.round(image.naturalWidth * scale))
const height = Math.max(1, Math.round(image.naturalHeight * scale))
canvas.width = width
canvas.height = height
ctx.clearRect(0, 0, width, height)
ctx.drawImage(image, 0, 0, width, height)
for (const quality of avatarQualitySteps) {
const blob = await canvasToBlob(canvas, 'image/webp', quality)
if (blob.size <= targetAvatarUploadBytes) {
const fileName = file.name.replace(/\.[^.]+$/, '') || 'avatar'
return new File([blob], `${fileName}.webp`, { type: 'image/webp' })
}
}
}
throw new Error(t('profile.avatar.compressTooLarge'))
}
async function prepareAvatarUpload(file: File): Promise<File> {
if (!file.type.startsWith('image/')) {
throw new Error(t('profile.avatar.invalidType'))
}
if (file.type === 'image/gif') {
if (file.size > targetAvatarUploadBytes) {
throw new Error(t('profile.avatar.gifTooLarge'))
}
return file
}
if (file.size <= targetAvatarUploadBytes) {
return file
}
return compressAvatarFile(file)
}
async function handleAvatarFileChange(event: Event) {
const input = event.target as HTMLInputElement | null
const file = input?.files?.[0]
@@ -360,7 +429,8 @@ async function handleAvatarFileChange(event: Event) {
}
try {
const dataURL = await readFileAsDataURL(file)
const preparedFile = await prepareAvatarUpload(file)
const dataURL = await readFileAsDataURL(preparedFile)
const normalized = validateAvatarInput(dataURL)
if (!normalized) {
return

View File

@@ -1,5 +1,5 @@
import { mount } from '@vue/test-utils'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import ProfileInfoCard from '@/components/user/profile/ProfileInfoCard.vue'
import type { User } from '@/types'
@@ -51,11 +51,15 @@ vi.mock('vue-i18n', async (importOriginal) => {
if (key === 'profile.avatar.inputLabel') return 'Avatar URL or data URL'
if (key === 'profile.avatar.inputPlaceholder') return 'https://cdn.example.com/avatar.png'
if (key === 'profile.avatar.uploadAction') return 'Upload image'
if (key === 'profile.avatar.uploadHint') return 'Images must be 100KB or smaller'
if (key === 'profile.avatar.uploadHint') return 'Images must be 100KB or smaller and will be compressed to 20KB'
if (key === 'profile.avatar.saveSuccess') return 'Avatar updated'
if (key === 'profile.avatar.deleteSuccess') return 'Avatar removed'
if (key === 'profile.avatar.invalidType') return 'Please choose an image file'
if (key === 'profile.avatar.fileTooLarge') return 'Avatar image must be 100KB or smaller'
if (key === 'profile.avatar.gifTooLarge') return 'GIF avatars must already be 20KB or smaller'
if (key === 'profile.avatar.compressTooLarge') return 'Unable to compress this image below 20KB'
if (key === 'profile.avatar.compressFailed') return 'Failed to compress the selected image'
if (key === 'profile.avatar.readFailed') return 'Failed to read the selected image'
if (key === 'profile.avatar.invalidValue') return 'Enter a valid avatar URL or image data URL'
if (key === 'profile.avatar.emptyDeleteHint') return 'Avatar already removed'
if (key === 'profile.authBindings.providers.email') return 'Email'
@@ -92,6 +96,63 @@ function createUser(overrides: Partial<User> = {}): User {
}
}
async function flushAsyncWork(): Promise<void> {
await Promise.resolve()
await Promise.resolve()
}
const originalFileReader = globalThis.FileReader
const originalImage = globalThis.Image
const originalCreateElement = document.createElement.bind(document)
function installAvatarCompressionMocks() {
class MockFileReader {
result: string | ArrayBuffer | null = null
onload: ((this: FileReader, ev: ProgressEvent<FileReader>) => any) | null = null
onerror: ((this: FileReader, ev: ProgressEvent<FileReader>) => any) | null = null
error: DOMException | null = null
readAsDataURL(blob: Blob) {
if (blob.type === 'image/webp') {
this.result = 'data:image/webp;base64,' + Buffer.from('compressed-avatar').toString('base64')
} else {
this.result = 'data:image/png;base64,' + Buffer.from('original-avatar').toString('base64')
}
this.onload?.call(this as unknown as FileReader, new ProgressEvent('load'))
}
}
class MockImage {
naturalWidth = 1200
naturalHeight = 1200
onload: (() => void) | null = null
onerror: (() => void) | null = null
set src(_value: string) {
this.onload?.()
}
}
globalThis.FileReader = MockFileReader as unknown as typeof FileReader
globalThis.Image = MockImage as unknown as typeof Image
vi.spyOn(document, 'createElement').mockImplementation(((tagName: string, options?: ElementCreationOptions) => {
if (tagName === 'canvas') {
return {
width: 0,
height: 0,
getContext: () => ({
clearRect: vi.fn(),
drawImage: vi.fn(),
}),
toBlob: (callback: BlobCallback) => {
callback(new Blob([new Uint8Array(8 * 1024)], { type: 'image/webp' }))
},
} as unknown as HTMLCanvasElement
}
return originalCreateElement(tagName, options)
}) as typeof document.createElement)
}
describe('ProfileInfoCard', () => {
beforeEach(() => {
updateProfileMock.mockReset()
@@ -100,6 +161,12 @@ describe('ProfileInfoCard', () => {
authStoreState.user = null
})
afterEach(() => {
globalThis.FileReader = originalFileReader
globalThis.Image = originalImage
vi.restoreAllMocks()
})
it('saves a remote avatar URL and updates the auth store', async () => {
const updatedUser = createUser({ avatar_url: 'https://cdn.example.com/new.png' })
updateProfileMock.mockResolvedValue(updatedUser)
@@ -148,6 +215,39 @@ describe('ProfileInfoCard', () => {
expect(showErrorMock).toHaveBeenCalledWith('Avatar image must be 100KB or smaller')
})
it('compresses uploaded images under 100KB before saving', async () => {
installAvatarCompressionMocks()
const updatedUser = createUser({ avatar_url: 'data:image/webp;base64,Y29tcHJlc3NlZC1hdmF0YXI=' })
updateProfileMock.mockResolvedValue(updatedUser)
authStoreState.user = createUser()
const wrapper = mount(ProfileInfoCard, {
props: {
user: authStoreState.user
},
global: {
stubs: {
Icon: true,
ProfileIdentityBindingsSection: true
}
}
})
const fileInput = wrapper.get('[data-testid="profile-avatar-file-input"]')
Object.defineProperty(fileInput.element, 'files', {
value: [new File([new Uint8Array(80 * 1024)], 'avatar.png', { type: 'image/png' })],
configurable: true
})
await fileInput.trigger('change')
await flushAsyncWork()
await wrapper.get('[data-testid="profile-avatar-save"]').trigger('click')
expect(updateProfileMock).toHaveBeenCalledWith({
avatar_url: 'data:image/webp;base64,Y29tcHJlc3NlZC1hdmF0YXI='
})
})
it('deletes the current avatar', async () => {
const updatedUser = createUser({ avatar_url: null })
updateProfileMock.mockResolvedValue(updatedUser)