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

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

$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:

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

But this error always shows:

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

Can anybody help?

+5
source share
2 answers

Although the late answer, but will be useful to future readers:

What you need to do:

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

This would mean that the browser will try to access it only when the data has been downloaded and will take care of AngularJS, and therefore you will no longer receive this error.

+4
source

The working approach to encoding base64 images is to use the Canvas and toDataURL() methods, but you need to load the image data from the server to the Image istance (via the src property). Here is an example:

 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 can base64-encoder your server- side image and return a response to the client already encoded. For example, in PHP:

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

Source: https://habr.com/ru/post/1237761/


All Articles