我想使用Angular.js (在离子框架中使用)转换从服务器获得的图像数据,我使用以下代码:
$http.post(link, {
token: token,
reservationCode: reservationCode
}).success(function (res){
$scope.image = btoa(unescape(encodeURIComponent(res)));
}).error(function (data) {
return false;
});
并在我的html中使用以下代码:
<img src="data:image/png;base64,{{image}}">
但是这个错误总是显示:
获取数据:image/png;base64 64,{图像} net::ERR_INVALID_URL
有人能帮忙吗?
发布于 2016-12-08 11:18:43
虽然答案迟了,但对将来的读者会有帮助:
你应该做的是:
<img ng-src="data:image/png;base64,{{image}}">
这意味着浏览器只有在加载数据并由AngularJS处理时才会尝试访问它,因此您将不再收到该错误。
发布于 2015-12-10 07:38:42
图像base64编码的一种工作方法是使用画布和toDataURL()
方法,但您需要将图像数据从服务器加载到图像 istance (通过src属性)。下面是一个示例:
function getBase64() {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext("2d");
var img = new Image();
img.onload = function () {
ctx.drawImage(img, 0, 0);
// pay attention: image here contains complete base 64 data url, no need for "data:image/png;base64," header...
$scope.image = canvas.toDataURL();
if (!$scope.$$phase) $scope.$apply();
};
img.src = "http://.../myImagepng";
}
最好您可以在base64服务器端上对图像进行编码,并将响应返回给已经编码的客户端。例如,在PHP中:
$pathToImg = 'myfolder/myimage.png';
$type = pathinfo($pathToImg, PATHINFO_EXTENSION);
$data = file_get_contents($pathToImg);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
https://stackoverflow.com/questions/34181961
复制相似问题