How can I strip the data:image part from a base64

2020-02-09 04:51发布

问题:

I am currently doing the following to decode base64 images in Javascript:

    var strImage = "";
    strImage = strToReplace.replace("data:image/jpeg;base64,", "");
    strImage = strToReplace.replace("data:image/png;base64,", "");
    strImage = strToReplace.replace("data:image/gif;base64,", "");
    strImage = strToReplace.replace("data:image/bmp;base64,", "");

As you can see above we are accepting the four most standard image types (jpeg, png, gif, bmp);

However, some of these images are very large and scanning through each one 4-5 times with replace seems a dreadful waste and terribly inefficient.

Is there a way I could reliably strip the data:image part of a base64 image string in a single pass?

Perhaps by detecting the first comma in the string?

Thanks in advance.

回答1:

You can use a regular expression:

var strImage = strToReplace.replace(/^data:image\/[a-z]+;base64,/, "");

  • ^ means At the start of the string
  • data:image means data:image
  • \/ means /
  • [a-z]+ means One or more characters between a and z
  • ;base64, means ;base64,


回答2:

var solution = string.split("base64,")[1];

Splits the variable string at "base64," than take the second part.



回答3:

This worked for me :

var strImage = strToReplace.split(',')[1];


回答4:

I came across this question looking for a way to strip any header. So just wanted to share this:

Regex.Replace(strToReplace, @"^.+?(;base64),", string.Empty))

Got this from an excellent answer which describes how to:

Match any characters as few as possible until a "abc" is found, without counting the "abc".



回答5:

use this regex

/[data:image\/[a-z]*;[a-z0-9]*,.*]/gm


回答6:

You can use startWith so you won't have to scan all the object. it's performance should be much better