dataURL file size larger than original file size. A who done it mystery solved.

dataURL file size larger than original file size. A who done it mystery solved.

Why is this dataURL so much larger than the original file size?!?! Spoiler alert: It was toDataURL in the canvas element with the file type conversion.

So you are using javascript either natively via the canvas element or through a library such as FabricJS to convert an image file into a dataURL. All appears well and you get your dataURL string created. Suddenly, you notice… the file size has ballooned to 3x the size of the original file. How has this happened? Is there anything I can do to prevent this?!?!

No need to freak out. This is not some alternate universe where dataURLs are always much larger than the original files.

The issue comes from the file type being converted when you created the dataURL. The toDataURL method of the HTMLCanvasElement defaults to “image/png” as the file type if you don’t provide one. So unless you do file type detection automatically or manually provide the correct file type to the method, it will convert the file to another format before creating the dataURL string. This file type conversion is the source of the ballooned file size.

Update your code to pass “image/jpeg” for jpg files, “image/png” for png files, “image/webp” for webp files, and so on. This will keep your dataURL size more in line with the original file size. You can still expect some minor increase due to a variety of factors that I do not pretend to fully understand but this will resolve your major issue.

You can pass a second parameter to the toDataURL method to specify a quality between 0 and 1. Using less than 1 will also reduce the size of the resulting file.

Hopefully, this saves you the hours of banging your head against the desk trying to figure out why the heck your files are blowing up in size each time you convert to dataURL.