Menu

Compress images in the browser before you upload them
📰

Compress images in the browser before you upload them

DEV Community: react·Msotafa Mohamed·4 days ago
#1ikdI0cj
#devtoreact#devto#dev#file#compressly
Reading 0:00
15s threshold

A modern phone photo is 4000 pixels wide and several megabytes. Your avatar slot is 128 pixels. Your product gallery shows images at 1600 pixels at most.

Most apps upload the full photo anyway, then resize it on the server. On a slow mobile connection, the user waits for megabytes they will never see, and you pay for the bandwidth and storage.

The browser can do the resizing itself before the upload starts. That's what compressly does.

The basic case

import { compressImage } from " compressly " ;

async function upload ( file : File ) { const small = await compressImage ( file , { maxWidth : 1600 , quality : 0.8 , targetSizeMB : 0.5 , mimeType : " image/webp " , });

const body = new FormData (); body . append ( " photo " , small ); await fetch ( " /api/upload " , { method : " POST " , body }); }

Enter fullscreen mode

Exit fullscreen mode

compressImage returns a regular File , so the rest of your upload code doesn't change.

The details that usually go wrong

Sideways photos.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.