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

How can I strip the data:image part from a base64 string of any image type 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,", "");

正如您在上面看到的,我们接受四种最标准的图像类型(jpeg、png、gif、bmp);

但是,其中一些图像非常大,用替换扫描每张图像 4-5 次似乎是一种可怕的浪费,而且效率极低。

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

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

提前致谢。

您可以使用正则表达式:

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

  • ^表示字符串开头
  • data:image表示data:image
  • \/ 表示 /
  • [a-z]+表示a和z之间的一个或多个字符
  • ;base64,表示;base64,
var solution = string.split("base64,")[1];

在 "base64," 处拆分变量字符串而不是第二部分。

这对我有用:

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

我在寻找一种方法来剥离任何 header 时遇到了这个问题。所以只想分享这个:

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

从一个优秀的 answer 那里得到这个,它描述了如何:

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

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

使用这个正则表达式

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

这对我有用 Swift 5:

let ourBase64String:String = "base64 string"
let base64StringArray:[String] = ourBase64String.components(separatedBy: "base64,")
if(attachmentArray.count > 0){
   print(attachmentArray[1])
}