2016-12-10 94 views
0

所以我有一个代码,图像编码到Base64一个..如何删除base64编码图像中的开始字符串?

function toDataUrl(url, callback) { 
    var xhr = new XMLHttpRequest(); 
    xhr.responseType = 'blob'; 
    xhr.onload = function() { 
     var reader = new FileReader(); 
     reader.onloadend = function() { 
     callback(reader.result); 
     } 
     reader.readAsDataURL(xhr.response); 
    }; 
    xhr.open('GET', url); 
    xhr.send(); 
    } 

    toDataUrl('img/no_image_icon.png', function(base64Img) { 
    console.log(base64Img); // remove the data:image/png;base64, in the beginning 
    }); 

此代码的工作,虽然我想删除data:image/png;base64,在生成base64Img的开始。另外,如何在功能外访问它? Like example

toDataUrl('img/no_image_icon.png', function(base64Img) { 
    var accessOutside = base64Img; // remove the data:image/png;base64, in the beginning 
    }); 

    var newVariable = accessOutside; 

任何帮助将不胜感激。

+0

[如何返回来自异步调用的响应?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/14220323 #14220323)你为什么要删除该标题? – Thomas

+0

@Thomas因为在我的前端代码(角)我已经有一个 – FewFlyBy

+0

第一:如果你已经使用角,看看[它的承诺](https://docs.angularjs.org/api/ng /服务/ $ q)*(承诺一般)*,和[我已经链接的线程](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from -an-asynchronous-call/14220323#14220323),这会帮助你解决异步问题。第二:你说,你在你的前端代码中添加头文件?不要这样做,那两个部分紧密地结合在一起。因此,您的前端只能使用base64编码的PNG,而不是任何图像的URL。你看到这是如何限制? – Thomas

回答

1

使用String.replace()方法

var base64Img = "data:image/png;base64,AAA="; 
 
base64Img = base64Img.replace("data:image/png;base64,", ""); 
 
console.log(base64Img);

+1

你可以更通用的替换:'/ data:。+?,/' – Thomas

1

首先,你需要将XHR改为同步请求。

xhr.open('GET', url, false); 

然后将accessOutside定义为全局变量。

toDataUrl('img/no_image_icon.png', function(base64Img) { 
    accessOutside = base64Img; // remove the data:image/png;base64, in the beginning 
    }); 

然后你可以从外面得到accessOutside值。

+0

我不知道你为什么需要从站点获取价值,最好把你的业务代码放在回调中,把xhr改成asyn。 – chaoluo

+0

不,请不要。这都是不好的做法/建议,最终会让你陷入屁股。 – Thomas

+0

这只是一种从外部获取价值的方法,最好将xhr更改为asyn并在回调函数中执行您的操作 – chaoluo

相关问题