Skip to content

🤯 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.

fix(utils): preserve JPEG format when compressing uploaded images (#13585)

Octopus65da232c64eb
diff --git a/packages/utils/src/compressImage.test.ts b/packages/utils/src/compressImage.test.ts
index ee07412aa28..22954a2552d 100644
--- a/packages/utils/src/compressImage.test.ts
+++ b/packages/utils/src/compressImage.test.ts
@@ -9,10 +9,12 @@ import compressImage, {
const getContextSpy = vi.spyOn(global.HTMLCanvasElement.prototype, 'getContext');
const drawImageSpy = vi.spyOn(CanvasRenderingContext2D.prototype, 'drawImage');
+const toDataURLSpy = vi.spyOn(global.HTMLCanvasElement.prototype, 'toDataURL');
beforeEach(() => {
getContextSpy.mockClear();
drawImageSpy.mockClear();
+ toDataURLSpy.mockClear();
});
describe('compressImage', () => {
@@ -58,6 +60,36 @@ describe('compressImage', () => {
expect(r).toMatch(/^data:image\/jpeg;base64,/);
});
+ it('should encode JPEG inputs as JPEG with 0.85 quality (preserve format, lossy)', () => {
+ const img = document.createElement('img');
+ img.width = 100;
+ img.height = 100;
+
+ compressImage({ img, type: 'image/jpeg' });
+
+ expect(toDataURLSpy).toHaveBeenCalledWith('image/jpeg', 0.85);
+ });
+
+ it('should encode non-JPEG inputs as PNG without a quality argument (lossless)', () => {
+ const img = document.createElement('img');
+ img.width = 100;
+ img.height = 100;
+
+ compressImage({ img, type: 'image/png' });
+
+ expect(toDataURLSpy).toHaveBeenCalledWith('image/png');
+ });
+
+ it('should default to PNG when no type is provided', () => {
+ const img = document.createElement('img');
+ img.width = 100;
+ img.height = 100;
+
+ compressImage({ img });
+
+ expect(toDataURLSpy).toHaveBeenCalledWith('image/png');
+ });
+
it('should support custom maxSize', () => {
const img = document.createElement('img');
img.width = 500;
@@ -139,6 +171,52 @@ describe('compressImageFile', () => {
global.Image = originalImage;
});
+ it('should preserve JPEG type when compressing large JPEG inputs (no PNG re-encoding)', async () => {
+ const file = createMockFile('photo.jpg', 'image/jpeg', 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);
+ // Output File MIME type must match the source format — previously this
+ // was hardcoded to 'image/png', which inflated photographic JPEGs.
+ expect(result.type).toBe('image/jpeg');
+ expect(result.name).toBe('photo.jpg');
+ expect(toDataURLSpy).toHaveBeenCalledWith('image/jpeg', 0.85);
+ global.Image = originalImage;
+ });
+
+ it('should preserve WebP inputs as PNG (existing fallback behaviour)', async () => {
+ const file = createMockFile('photo.webp', 'image/webp', 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);
+ // WebP isn't supported as a canvas output target, so we still fall back
+ // to lossless PNG. Documents the deliberate choice.
+ expect(result.type).toBe('image/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);
diff --git a/packages/utils/src/compressImage.ts b/packages/utils/src/compressImage.ts
index 780737e35b3..b798067edb9 100644
--- a/packages/utils/src/compressImage.ts
+++ b/packages/utils/src/compressImage.ts
@@ -3,6 +3,9 @@ export const MAX_IMAGE_BYTES = 5 * 1024 * 1024; // 5MB
export const COMPRESSIBLE_IMAGE_TYPES = new Set(['image/jpeg', 'image/png', 'image/webp']);
+// JPEG quality for canvas re-encoding (0.85 balances size and quality)
+const JPEG_QUALITY = 0.85;
+
const compressImage = ({
img,
type,
@@ -33,16 +36,23 @@ const compressImage = ({
ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, width, height);
- return canvas.toDataURL(type);
+ // Preserve JPEG format with lossy compression to avoid inflating small JPEGs;
+ // fall back to PNG for other formats (lossless and universally supported).
+ if (type === 'image/jpeg') {
+ return canvas.toDataURL('image/jpeg', JPEG_QUALITY);
+ }
+ return canvas.toDataURL('image/png');
};
export default compressImage;
const dataUrlToFile = (dataUrl: string, name: string): File => {
+ // Extract the actual MIME type from the data URL to keep content and type consistent
+ const mimeType = dataUrl.split(',')[0].split(':')[1].split(';')[0];
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' });
+ return new File([bytes], name, { type: mimeType });
};
export const compressImageFile = (file: File): Promise<File> =>
@@ -67,7 +77,7 @@ export const compressImageFile = (file: File): Promise<File> =>
let maxSize = MAX_IMAGE_SIZE;
let result: File;
do {
- const dataUrl = compressImage({ img, maxSize });
+ const dataUrl = compressImage({ img, maxSize, type: file.type });
result = dataUrlToFile(dataUrl, file.name);
maxSize = Math.round(maxSize * 0.8);
} while (result.size > MAX_IMAGE_BYTES && maxSize > 100);