在Angularjs中将字节数组转换为Base64字符串

4

我在服务响应中得到了字节数组,这个图像会显示在我的HTML页面的图像字段中。有什么实现方法吗?我试图在Stack Overflow上找到解决方案,但没有找到有效的解决方案。请帮忙。我的代码如下:

this.getPrescription = function(pres_id) {
     var deff = $q.defer();
     $http({
           method: "GET",
           url: "www.abc.com/api/&prescriptionOnly=false&page=1",
           headers: {
           'Authorization': 'Bearer ' + localStorage.getItem("chemist_access_token"),
           'Content-Type': 'application/json'
           },
           responseType: 'arraybuffer'
           }).then(function(objS) {
                   console.log("getPrescription:\n" + JSON.stringify(objS))
                   deff.resolve(objS);
                   }, function(objE) {
                   errorHandler.serverErrorhandler(objE);
                   deff.reject(objE);
                   });
     return deff.promise;
     };

在我的控制器中,我正在这样调用:

$scope.getPrescription = function(id) {
    $ionicLoading.show({
        template: '<ion-spinner icon="spiral"></ion-spinner>',
        noBackdrop: false
    });
    serverRepo.prescriptionGet(id).then(function(objS) {
        console.log("orderByCustomer:\n" + JSON.stringify(objS));
        $scope.picdata=$window.URL.createObjectURL(new Blob([objS.data], {type: 'image/png'}));

        $ionicLoading.hide();
        console.log("getOrderByNew_success_loadMore:\n" +$scope.picdata);
    }, function(objE) {
        $ionicLoading.hide();
    });
}

当我检查控制台时,它显示如下内容: getOrderByNew_success_loadMore: blob:file:///0aa86d9f-61a1-4049-b18c-7bf81e05909f


尝试这样做: <img src="data:image/jpg;base64,{{yourData}}" /> - Hadi J
您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Anjaney Mishra
如何在控制台中显示图片数据? - Hadi J
2个回答

8
使用此过滤器将字节数组转换为base64。
app.filter('bytetobase', function () {
    return function (buffer) {
        var binary = '';
        var bytes = new Uint8Array(buffer);
        var len = bytes.byteLength;
        for (var i = 0; i < len; i++) {
            binary += String.fromCharCode(bytes[i]);
        }
        return window.btoa(binary);
    };
});

要将其绑定为图像,请使用

<img ng-src="data:image/JPEG;base64,{{picture | bytetobase}}" alt="..." width="100" height="100">

如果您需要将其赋值给变量,请使用以下方法

var image = $filter('bytetobase')($scope.picture );

3
如果您需要从字节数组显示图像,可以使用 Blob 创建一个对象并获取其 URL,然后将 URL 传递给图像标签源。Blob 构造函数中的最后一个参数包含有关 Blob 类型的信息,在 Blob 创建过程中应设置正确的类型。
$http.get(url, {responseType: 'arraybuffer'})
  .then(function(response) {
    return $window.URL.createObjectURL(new Blob([response.data], {type: 'image/png'}));
  });

当您不再计划使用对象时(例如,在适当的img标记中加载图像后),请执行以下操作:

更新

使用base64的替代解决方案

$scope.getPrescription = function(id) {
  $ionicLoading.show({
    template: '<ion-spinner icon="spiral"></ion-spinner>',
    noBackdrop: false
  });
  serverRepo.prescriptionGet(id).then(function(objS) {
    console.log("orderByCustomer:\n" + JSON.stringify(objS));
    // Creating file reader
    var reader = new window.FileReader();
    // Creating blob from server's data
    var data = new Blob([objS.data], {type: 'image/jpeg'});
    // Starting reading data
    reader.readAsDataURL(data); 
    // When all data was read
    reader.onloadend = function() {
      // Setting source of the image
      $scope.picdata = reader.result;
      // Forcing digest loop
      $scope.$apply();
    }

    $ionicLoading.hide();
    console.log("getOrderByNew_success_loadMore:\n" +$scope.picdata);
    }, function(objE) {
    $ionicLoading.hide();
  });
}

我这样运行函数:-serverRepo.prescriptionGet(id).then(function(objS) { $scope.picdata=$window.URL.createObjectURL(new Blob([objS.data], {type: 'image/png'})); },function(err){});以下是HTML代码:-<center><img ng-src="{{picdata}}"/></center> 我从函数中得到了以下响应:-blob:file:///a3831c70-79ef-42db-8c9e-6d3548ca1bf2 - Anjaney Mishra
在get请求中忘记添加responseType参数 $http.get(url, {responseType: 'arraybuffer'}) - k10der
我在我的服务调用中添加了responseType,但是返回的URL在<img>中没有显示图像。 - Anjaney Mishra
你确定在 $http.get 调用中添加了 {responseType: 'arraybuffer'},而不是 prescriptionGet 吗?请检查浏览器控制台以查看是否出现任何错误。 - k10der
我在我的问题中进行了更改。将我的代码放入问题中。请检查并告诉我我犯了什么错误。 - Anjaney Mishra
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接