如何从Javascript中任何图像类型的base64字符串中剥离数据:图像部分
我目前正在执行以下操作以在 Javascript 中解码 base64 图像:
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,", "");
正如您在上面看到的,我们接受四种最标准的图像类型(jpeg、png、gif、bmp);
As you can see above we are accepting the four most standard image types (jpeg, png, gif, bmp);
但是,其中一些图像非常大,用替换扫描每张图像 4-5 次似乎是一种可怕的浪费,而且效率极低.
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.
有没有一种方法可以可靠地一次性剥离 base64 图像字符串的 data:image 部分?
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?
提前致谢.
推荐答案
可以使用正则表达式:
var strImage = strToReplace.replace(/^data:image/[a-z]+;base64,/, "");
<小时>
^
表示在字符串的开头data:image
表示 data:image/
表示 /[a-z]+
表示a和z之间的一个或多个字符;base64,
表示 ;base64,^
means At the start of the stringdata:image
means data:image/
means /[a-z]+
means One or more characters between a and z;base64,
means ;base64,
相关文章