如何从 Javascript 中任何图像类型的 base64 字符串中去除 data:image 部分

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38633061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:40:56  来源:igfitidea点击:

How can I strip the data:image part from a base64 string of any image type in Javascript

javascriptstringimagebase64

提问by Sergio Domínguez

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

我目前正在执行以下操作以在 Javascript 中解码 base64 图像:

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

正如您在上面看到的,我们接受四种最标准的图像类型(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.

然而,这些图像中的一些非常大,使用替换扫描每个图像 4-5 次似乎是一种可怕的浪费并且非常低效。

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

有没有一种方法可以在一次通过中可靠地去除 base64 图像字符串的 data:image 部分?

Perhaps by detecting the first comma in the string?

也许通过检测字符串中的第一个逗号?

Thanks in advance.

提前致谢。

回答by Nicolò

You can use a regular expression:

您可以使用正则表达式:

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


  • ^means At the start of the string
  • data:imagemeans data:image
  • \/means /
  • [a-z]+means One or more characters between a and z
  • ;base64,means ;base64,
  • ^表示在字符串的开头
  • data:image表示数据:图像
  • \/表示/
  • [a-z]+表示a 和 z 之间的一个或多个字符
  • ;base64,意思是;base64,

回答by Jonas Wilms

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

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

在“base64”处拆分变量字符串,而不是采用第二部分。

回答by Adrita Sharma

This worked for me :

这对我有用:

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

回答by Daan van Hulst

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 answerwhich describes how to:

从一个很好的答案中得到了这个,它描述了如何:

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

尽可能少地匹配任何字符,直到找到“abc”,而不计算“abc”。

回答by karzan osman

use this regex

使用这个正则表达式

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

回答by Amor

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

您可以使用startWith这样您就不必扫描所有对象。它的性能应该好得多