如何用blob图像url显示图像?

时间:2018-04-08 06:07:18

标签: angularjs ng-file-upload bonita

我有图片的blob网址,想要显示它。 我尝试过的一种方法是使用 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);

}

我得到的blobl网址是 ng-file-upload 7.2.2

2 个答案:

答案 0 :(得分:0)

如果你需要从url获取blob:

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); 
});

但是因为你已经有了这个blob

 $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);

}

答案 1 :(得分:0)

您也可以尝试

$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);
    });           
}