🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix: compress uploaded images to max 1920px before sending to API (#13224)
Arvin Xu007d2dc5549b
diff --git a/packages/utils/src/compressImage.test.ts b/packages/utils/src/compressImage.test.tsindex e7f921b6093..ee07412aa28 100644--- a/packages/utils/src/compressImage.test.ts+++ b/packages/utils/src/compressImage.test.ts@@ -1,6 +1,11 @@import { beforeEach, describe, expect, it, vi } from 'vitest';-import compressImage from './compressImage';+import compressImage, {+ COMPRESSIBLE_IMAGE_TYPES,+ compressImageFile,+ MAX_IMAGE_BYTES,+ MAX_IMAGE_SIZE,+} from './compressImage';const getContextSpy = vi.spyOn(global.HTMLCanvasElement.prototype, 'getContext');const drawImageSpy = vi.spyOn(CanvasRenderingContext2D.prototype, 'drawImage');@@ -11,51 +16,163 @@ beforeEach(() => {});describe('compressImage', () => {- it('should compress image with maxWidth', () => {+ it('should compress image when width exceeds maxSize', () => {const img = document.createElement('img');img.width = 3000;img.height = 2000;const r = compressImage({ img });- expect(r).toMatch(/^data:image\/webp;base64,/);-- expect(getContextSpy).toBeCalledTimes(1);- expect(getContextSpy).toBeCalledWith('2d');-- expect(drawImageSpy).toBeCalledTimes(1);- expect(drawImageSpy).toBeCalledWith(img, 0, 0, 3000, 2000, 0, 0, 2160, 1440);+ expect(r).toMatch(/^data:image\/png;base64,/);+ expect(drawImageSpy).toBeCalledWith(img, 0, 0, 3000, 2000, 0, 0, 1920, 1280);});- it('should compress image with maxHeight', () => {+ it('should compress image when height exceeds maxSize', () => {const img = document.createElement('img');img.width = 2000;img.height = 3000;const r = compressImage({ img });- expect(r).toMatch(/^data:image\/webp;base64,/);+ expect(r).toMatch(/^data:image\/png;base64,/);+ expect(drawImageSpy).toBeCalledWith(img, 0, 0, 2000, 3000, 0, 0, 1280, 1920);+ });++ it('should not compress image when within maxSize', () => {+ const img = document.createElement('img');+ img.width = 1800;+ img.height = 1800;- expect(getContextSpy).toBeCalledTimes(1);- expect(getContextSpy).toBeCalledWith('2d');+ compressImage({ img });- expect(drawImageSpy).toBeCalledTimes(1);- expect(drawImageSpy).toBeCalledWith(img, 0, 0, 2000, 3000, 0, 0, 1440, 2160);+ expect(drawImageSpy).toBeCalledWith(img, 0, 0, 1800, 1800, 0, 0, 1800, 1800);});- it('should not compress image', () => {+ it('should use specified output type', () => {const img = document.createElement('img');- img.width = 2000;- img.height = 2000;+ img.width = 100;+ img.height = 100;- const r = compressImage({ img });+ const r = compressImage({ img, type: 'image/jpeg' });++ expect(r).toMatch(/^data:image\/jpeg;base64,/);+ });++ it('should support custom maxSize', () => {+ const img = document.createElement('img');+ img.width = 500;+ img.height = 300;++ compressImage({ img, maxSize: 400 });++ expect(drawImageSpy).toBeCalledWith(img, 0, 0, 500, 300, 0, 0, 400, 240);+ });+});++describe('COMPRESSIBLE_IMAGE_TYPES', () => {+ it('should include jpeg, png, webp', () => {+ expect(COMPRESSIBLE_IMAGE_TYPES.has('image/jpeg')).toBe(true);+ expect(COMPRESSIBLE_IMAGE_TYPES.has('image/png')).toBe(true);+ expect(COMPRESSIBLE_IMAGE_TYPES.has('image/webp')).toBe(true);+ });++ it('should exclude gif and svg', () => {+ expect(COMPRESSIBLE_IMAGE_TYPES.has('image/gif')).toBe(false);+ expect(COMPRESSIBLE_IMAGE_TYPES.has('image/svg+xml')).toBe(false);+ });+});++describe('constants', () => {+ it('MAX_IMAGE_SIZE should be 1920', () => {+ expect(MAX_IMAGE_SIZE).toBe(1920);+ });++ it('MAX_IMAGE_BYTES should be 5MB', () => {+ expect(MAX_IMAGE_BYTES).toBe(5 * 1024 * 1024);+ });+});++describe('compressImageFile', () => {+ const createMockFile = (name: string, type: string, size: number) => {+ const content = new Uint8Array(size);+ return new File([content], name, { type });+ };++ it('should skip compression for small images', async () => {+ const file = createMockFile('small.png', 'image/png', 1000);++ // Mock Image load with small dimensions+ const originalImage = global.Image;+ global.Image = class MockImage extends originalImage {+ constructor() {+ super();+ Object.defineProperty(this, 'width', { value: 800, writable: false });+ Object.defineProperty(this, 'height', { value: 600, writable: false });+ setTimeout(() => this.dispatchEvent(new Event('load')), 0);+ }+ } as any;++ const result = await compressImageFile(file);++ expect(result).toBe(file); // same reference, no compression+ global.Image = originalImage;+ });++ it('should compress images exceeding max dimensions', async () => {+ const file = createMockFile('large.png', 'image/png', 1000);++ const originalImage = global.Image;+ global.Image = class MockImage extends originalImage {+ constructor() {+ super();+ Object.defineProperty(this, 'width', { value: 3000, writable: false });+ Object.defineProperty(this, 'height', { value: 2000, writable: false });+ setTimeout(() => this.dispatchEvent(new Event('load')), 0);+ }+ } as any;++ const result = await compressImageFile(file);++ expect(result).not.toBe(file);+ expect(result.type).toBe('image/png');+ expect(result.name).toBe('large.png');+ global.Image = originalImage;+ });++ it('should compress images exceeding max file size even if dimensions are small', async () => {+ const file = createMockFile('heavy.png', 'image/png', 6 * 1024 * 1024);++ const originalImage = global.Image;+ global.Image = class MockImage extends originalImage {+ constructor() {+ super();+ Object.defineProperty(this, 'width', { value: 1800, writable: false });+ Object.defineProperty(this, 'height', { value: 1800, writable: false });+ setTimeout(() => this.dispatchEvent(new Event('load')), 0);+ }+ } as any;++ const result = await compressImageFile(file);++ expect(result).not.toBe(file);+ expect(result.type).toBe('image/png');+ global.Image = originalImage;+ });++ it('should resolve original file on load error', async () => {+ const file = createMockFile('broken.png', 'image/png', 1000);- expect(r).toMatch(/^data:image\/webp;base64,/);+ const originalImage = global.Image;+ global.Image = class MockImage extends originalImage {+ constructor() {+ super();+ setTimeout(() => this.dispatchEvent(new Event('error')), 0);+ }+ } as any;- expect(getContextSpy).toBeCalledTimes(1);- expect(getContextSpy).toBeCalledWith('2d');+ const result = await compressImageFile(file);- expect(drawImageSpy).toBeCalledTimes(1);- expect(drawImageSpy).toBeCalledWith(img, 0, 0, 2000, 2000, 0, 0, 2000, 2000);+ expect(result).toBe(file);+ global.Image = originalImage;});});diff --git a/packages/utils/src/compressImage.ts b/packages/utils/src/compressImage.tsindex 79d0daa78d0..780737e35b3 100644--- a/packages/utils/src/compressImage.ts+++ b/packages/utils/src/compressImage.ts@@ -1,18 +1,28 @@-const compressImage = ({ img, type = 'image/webp' }: { img: HTMLImageElement; type?: string }) => {- // Set maximum width and height- const maxWidth = 2160;- const maxHeight = 2160;+export const MAX_IMAGE_SIZE = 1920;+export const MAX_IMAGE_BYTES = 5 * 1024 * 1024; // 5MB++export const COMPRESSIBLE_IMAGE_TYPES = new Set(['image/jpeg', 'image/png', 'image/webp']);++const compressImage = ({+ img,+ type,+ maxSize = MAX_IMAGE_SIZE,+}: {+ img: HTMLImageElement;+ maxSize?: number;+ type?: string;+}) => {let width = img.width;let height = img.height;- if (width > height && width > maxWidth) {- // If image width is greater than height and exceeds maximum width limit- width = maxWidth;- height = Math.round((maxWidth / img.width) * img.height);- } else if (height > width && height > maxHeight) {- // If image height is greater than width and exceeds maximum height limit- height = maxHeight;- width = Math.round((maxHeight / img.height) * img.width);+ if (width > maxSize || height > maxSize) {+ if (width >= height) {+ height = Math.round((maxSize / width) * height);+ width = maxSize;+ } else {+ width = Math.round((maxSize / height) * width);+ height = maxSize;+ }}const canvas = document.createElement('canvas');@@ -27,3 +37,48 @@ const compressImage = ({ img, type = 'image/webp' }: { img: HTMLImageElement; ty};export default compressImage;++const dataUrlToFile = (dataUrl: string, name: string): File => {+ const binary = atob(dataUrl.split(',')[1]);+ const bytes = new Uint8Array(binary.length);+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);+ return new File([bytes], name, { type: 'image/png' });+};++export const compressImageFile = (file: File): Promise<File> =>+ new Promise((resolve) => {+ const img = new Image();+ const objectUrl = URL.createObjectURL(file);++ img.addEventListener('load', () => {+ URL.revokeObjectURL(objectUrl);++ // skip if image is small enough in both dimensions and file size+ if (+ img.width <= MAX_IMAGE_SIZE &&+ img.height <= MAX_IMAGE_SIZE &&+ file.size <= MAX_IMAGE_BYTES+ ) {+ resolve(file);+ return;+ }++ // progressively shrink until under 5MB+ let maxSize = MAX_IMAGE_SIZE;+ let result: File;+ do {+ const dataUrl = compressImage({ img, maxSize });+ result = dataUrlToFile(dataUrl, file.name);+ maxSize = Math.round(maxSize * 0.8);+ } while (result.size > MAX_IMAGE_BYTES && maxSize > 100);++ resolve(result);+ });++ img.addEventListener('error', () => {+ URL.revokeObjectURL(objectUrl);+ resolve(file);+ });++ img.src = objectUrl;+ });diff --git a/src/store/file/slices/chat/action.ts b/src/store/file/slices/chat/action.tsindex 2aba7c0384f..ba5efba35ec 100644--- a/src/store/file/slices/chat/action.ts+++ b/src/store/file/slices/chat/action.ts@@ -1,4 +1,5 @@import { type ChatContextContent } from '@lobechat/types';+import { COMPRESSIBLE_IMAGE_TYPES, compressImageFile } from '@lobechat/utils/compressImage';import { t } from 'i18next';import { notification } from '@/components/AntdStaticMethods';@@ -108,8 +109,14 @@ export class FileActionImpl {uploadChatFiles = async (rawFiles: File[]): Promise<void> => {const { dispatchChatUploadFileList } = this.#get();// 0. skip file in blacklist- const files = rawFiles.filter((file) => !FILE_UPLOAD_BLACKLIST.includes(file.name));- // 1. add files with base64+ const filteredFiles = rawFiles.filter((file) => !FILE_UPLOAD_BLACKLIST.includes(file.name));+ // 1. compress images and add files with base64+ const files = await Promise.all(+ filteredFiles.map((file) =>+ COMPRESSIBLE_IMAGE_TYPES.has(file.type) ? compressImageFile(file) : file,+ ),+ );+const uploadFiles: UploadFileItem[] = await Promise.all(files.map(async (file) => {let previewUrl: string | undefined = undefined;