Skip to content
Lucky Snail Logo Lucky Snail
中文

Pure Frontend: Ultra-Fast, Stable Compression for Extra-Large Images

/ 2 min read /
#图片压缩
Table of Contents 目录

Background

Let me show you the compression result first — looks great, right? Now let’s see how to implement it!

image-20240824221714151

In a recent project, our users might upload very large images. If we directly tell them the upload failed or forbid large images, that wouldn’t be very user-friendly — users would have to compress the image themselves and then come back to upload, adding friction to the system. So I asked the backend team to handle image compression on the server side, but they said compressing images is resource-intensive and suggested using a third-party paid service instead. That got me thinking: can we implement image compression on the client side? After all, client-side compression has many advantages!

Why is client-side compression better than server-side compression?

  1. Reduces server load: Offloading compression to the client significantly eases the pressure on our servers. User resources are free, but server resources cost real money.

  2. Improves user experience: Instead of uploading a huge file to the server, we send a much smaller one — this is especially friendly for users with poor network connections.

  3. Real-time preview of compression results: If you need to show the compressed result, client-side compression lets users see it instantly. With server-side compression, the large image must first be uploaded, then compressed on the server, and then the small result is returned — by the time the client displays it, users might have fallen asleep…

Implementation

Do you ever need to compress images? What tools do you use? Here are two excellent online image compression services I can recommend:

The second one is an open-source compression service by Google, running entirely on the client side — all processing is local, safe and fast. My implementation below also relies on it.

Google’s open-source code is here: https://github.com/GoogleChromeLabs/squoosh

Some clever people have wrapped it into a package that makes it super easy to use in frontend projects: https://github.com/ElonXun/squoosh-compress

So we just install that package and compress images following the docs. I’ve written a sample usage demo for reference:

https://github.com/chaseFunny/image-compression

END

Does anyone have a better way to implement image compression? And do you think it’s better to compress on the client side or the server side?