获取数据:image/png; base64,{{image}} net :: ERR_INVALID_URL

Red*_*rbo 6 javascript html5 angularjs ionic-framework

我想转换使用Angular.js从服务器获取的图像数据(用于离子框架),我使用此代码:

$http.post(link, {
          token: token,
          reservationCode: reservationCode
          }).success(function (res){
            $scope.image = btoa(unescape(encodeURIComponent(res)));

        }).error(function (data) {
          return false;
        }); 
Run Code Online (Sandbox Code Playgroud)

并在我的HTML中使用此代码:

  <img src="data:image/png;base64,{{image}}">
Run Code Online (Sandbox Code Playgroud)

但是这个错误总是显示:

获取数据:image/png; base64,{{image}} net :: ERR_INVALID_URL

有人可以帮忙吗?

Pri*_*jee 6

虽然答案很晚,但对未来的读者会有所帮助:

你应该做的是:

 <img ng-src="data:image/png;base64,{{image}}">
Run Code Online (Sandbox Code Playgroud)

这意味着浏览器只有在加载数据时才会尝试访问它,AngularJS会对其进行处理,因此您不会再出现该错误.


bea*_*ver 0

对图像进行 Base64 编码的一种工作方法是使用CanvastoDataURL()方法,但您需要将图像数据从服务器加载到图像实例(通过 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";
}
Run Code Online (Sandbox Code Playgroud)

最好您可以在服务器端将图像编码为 Base64 ,并将已编码的响应返回给客户端。以 PHP 为例:

$pathToImg = 'myfolder/myimage.png';
$type = pathinfo($pathToImg, PATHINFO_EXTENSION);
$data = file_get_contents($pathToImg);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
Run Code Online (Sandbox Code Playgroud)