Image file size from data URI in JavaScript

后端 未结 4 1221
野趣味
野趣味 2020-12-18 11:19

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:

相关标签:
4条回答
  • 2020-12-18 11:54

    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);
    
    0 讨论(0)
  • 2020-12-18 12:07

    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.

    0 讨论(0)
  • 2020-12-18 12:11

    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.

    0 讨论(0)
  • 2020-12-18 12:19

    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);

    0 讨论(0)
提交回复
热议问题