young-ceo
young-ceo

Reputation: 5384

Image file size from data URI in JavaScript

I am not sure it's even possible but - can I get the image file size from data URI?

For example, let's say there is an IMG element where src goes:

src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD...

Based on the src, can I get the image file size by using plain JavaScript? (without server request)

Upvotes: 7

Views: 16412

Answers (5)

Nadav
Nadav

Reputation: 1145

The other solutions make use of atob, which has now been deprecated. Here is an up-to-date example, using Buffer instead.

const src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD...";
const base64str = src.split('base64,')[1]; //remove the image type metadata.
const imageFile = Buffer.from(base64str, 'base64'); //encode image into bytes
console.log('FileSize: ' + imageFile.length);

Upvotes: 2

Deyl Raytop
Deyl Raytop

Reputation: 51

This is a universal solution for all types of base64 strings based on Daniel Trans's code.

var src ="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP/// yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";

var base64str = src.split('base64,')[1];
var decoded = atob(base64str);

console.log("FileSize: " + decoded.length);

Upvotes: 3

AuxTaco
AuxTaco

Reputation: 5171

If you're okay with a (very good) estimate, the file size is 75% of the size of the base64 string. The true size is no larger than this estimate, and, at most, two bytes smaller.

If you want to write one line and be done with it, use atob() and check the length, as in the other answers.

If you want an exact answer with maximum performance (in the case of gigantic files or millions of files or both), use the estimate but account for the padding to get the exact size:

let base64Length = src.length - (src.indexOf(',') + 1);
let padding = (src.charAt(src.length - 2) === '=') ? 2 : ((src.charAt(src.length - 1) === '=') ? 1 : 0);
let fileSize = base64Length * 0.75 - padding;

This avoids parsing the entire string, and is entirely overkill unless you're hunting for microoptimizations or are short on memory.

Upvotes: 11

Deepak Kamat
Deepak Kamat

Reputation: 1980

Your best option is to calculate the length of the base64 string itself.

What is a base64 length in bytes?

You have to convert the base64 string to a normal string using atob() and then check it length, it will return a value that you can say is close to the actual size of the image. Also you don't need the data:image/jpeg;base64, part from the data URI to check the size.

Upvotes: 3

Daniel Tran
Daniel Tran

Reputation: 6171

If you want file size, simply decode your base64 string and check the length.

var src ="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP/// yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";

var base64str = src.substr(22);
var decoded = atob(base64str);

console.log("FileSize: " + decoded.length);

Upvotes: 25

Related Questions