javascript 获取数据:图像/png;base64,{{图像}} net::ERR_INVALID_URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34181961/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 17:21:12  来源:igfitidea点击:

GET data:image/png;base64,{{image}} net::ERR_INVALID_URL

javascriptangularjshtmlionic-framework

提问by Redturbo

I want to convert image data that I get from server using Angular.js (for use in ionic-framework), I have use this code :

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

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

        }).error(function (data) {
          return false;
        }); 

And use this code in my html :

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

  <img src="data:image/png;base64,{{image}}">

But this error always show :

但是这个错误总是显示:

GET data:image/png;base64,{{image}} net::ERR_INVALID_URL

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

anybody can help ?

有人可以帮忙吗?

回答by Pritam Banerjee

Though a late answer, but will be helpful for future readers:

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

What you should do is:

你应该做的是:

 <img ng-src="data:image/png;base64,{{image}}">

That would mean that the browser will try to access it only when the data is loaded and will be taken care by AngularJS and hence you will not get that error anymore.

这意味着浏览器只会在加载数据时尝试访问它,并且会由 AngularJS 处理,因此您不会再收到该错误。

回答by beaver

A working approach to base64 encoding of images is to use Canvasand toDataURL()method, but you need to load your image data from server to an Imageistance (via src property). Here is an example:

对图像进行 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";
}

Preferably you could encode to base64 your image on the server sideand return the response to the client already encoded. For example in PHP:

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

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