How can I strip the data:image part from a base64 string of any image type in Javascript(如何从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,
这篇关于如何从Javascript中任何图像类型的base64字符串中剥离数据:图像部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从Javascript中任何图像类型的base64字符串中剥离数据:图像部分


- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06