I want to convert image data that I get from server using Angular.js (for use in ionic-framework), I have 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 show :
GET data:image/png;base64,{{image}} net::ERR_INVALID_URL
anybody can help ?
I want to convert image data that I get from server using Angular.js (for use in ionic-framework), I have 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 show :
GET data:image/png;base64,{{image}} net::ERR_INVALID_URL
anybody can help ?
Share Improve this question edited Mar 15, 2017 at 9:11 Pritam Banerjee 18.9k10 gold badges96 silver badges112 bronze badges asked Dec 9, 2015 at 14:58 RedturboRedturbo 1,6139 gold badges24 silver badges36 bronze badges 1- 2 You should really be using ngSrc. Not sure that will fix your specific issue though. – Matthew Green Commented Dec 9, 2015 at 15:03
2 Answers
Reset to default 8Though 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.
A working approach to base64 encoding of images is to use Canvas and toDataURL()
method, but you need to load your image data from server to an Image istance (via 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 plete 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 side and return the 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);