1

I have blob url for image and want to display it. One method I tried is by using createObjectURL().

 $scope.preview = function(path) {
        //path is 'data:image/jpeg;base64,/9j/4QAYRXhpZgAASUkqAAgAAAA....'
        var file = new Blob([ path ], {  
            type : 'image/jpeg'
        });
        var fileURL = URL.createObjectURL(file); 
        //fileURL is blob:http://localhost:8080/a8610a32-521f-407c-8f....
        console.log('fileurl: ', fileURL);
        $('img.image-preview').attr('ng-src', fileURL);

}

The blobl url I am getting is by ng-file-upload 7.2.2.

YaSh Chaudhary
  • 2,605
  • 8
  • 37
  • 74
  • You mix angularjs call with jQuery which is not good practice. when you add `ng-src` attribute using jquery `attr()`, angularjs does not know automatically about this DOM change. – Zamrony P. Juhara Apr 08 '18 at 06:16

2 Answers2

0

in case you need to get blob from url :

var config = { responseType: 'blob' };
$http.get(itemsUrl, config).then(function onSuccess(response) {
    var blob = response.data;
    var contentType = response.headers("content-type");
  $scope.createImageFromBlob(blob); 
});

but since you have that blob already

 $scope.preview = function(path) {
        //path is 'data:image/jpeg;base64,/9j/4QAYRXhpZgAASUkqAAgAAAA....'
        var file = new Blob([ path ], {  
            type : 'image/jpeg'
        });

        $scope.createImageFromBlob(file)

}

$scope.createImageFromBlob(blob) {
    let reader = new FileReader();
    reader.addEventListener('load', () => {
       let photo = reader.result;
       $scope.Imagebase64 = photo.replace('data:image/jpeg;base64','data:image/gif;base64');
    }, false);
       reader.readAsDataURL(blob);

}
Arash
  • 3,458
  • 7
  • 32
  • 50
0

You can also try this

$scope.preview = function(path) {
    $http.get(path)
       .then(function(response) {
           $scope.image = "data:image/jpg;base64," + btoa(String.fromCharCode.apply(null, new Uint8Array(response.data)));
           $('img.image-preview').attr('ng-src', $scope.image);
    });           
}