简体   繁体   English

从Java的Azure Blob存储下载数据后,如何在图像中嵌入base64编码的数据?

[英]How to embed base64 encoded data in image after downloading data from Azure Blob Storage in Javascript?

I'm trying to embed an image using the base64 data pattern, instead of a URL reference. 我正在尝试使用base64数据模式而不是URL引用嵌入图像。 I first download the data from Azure Blob storage, using the Azure Node.js SDK: 我首先使用Azure Node.js SDK从Azure Blob存储下载数据:

https://azure.microsoft.com/en-us/documentation/articles/storage-nodejs-how-to-use-blob-storage/#download-blobs https://azure.microsoft.com/zh-CN/documentation/articles/storage-nodejs-how-to-use-blob-storage/#download-blobs

From what I can tell the data downloads as a string. 据我所知,数据下载是一个字符串。 But I'm not sure what to do with the string to get it into base64. 但是我不确定如何处理字符串以使其进入base64。

I need to encode the data as base64 and set the image source attribute. 我需要将数据编码为base64并设置图像源属性。 How do I do that? 我怎么做?

Here is a snippet that shows what happens when I try to just embed the downloaded data directly: 这是一个片段,显示了当我尝试直接嵌入下载的数据时会发生的情况:

        cameraContainer.listBlobsSegmentedWithPrefix($routeParams.cameraId, path, null, options, function(error, result, response) {
        result.entries.forEach(function(entry) {
            $http.get(containerUrl + "/" + $routeParams.cameraId + "/" + entry.name + containerToken)
                .then(function(successResponse) {
                    $scope.camera.imageUrl = "data:image/jpeg;base64," + successResponse.data;
                }, function(errorResponse) {

                });
        });
    });

I end up getting this error in the browser: 我最终在浏览器中收到此错误:

在此处输入图片说明

Also, if I try executing the following JS: 另外,如果我尝试执行以下JS:

console.log(decodeURIComponent(successResponse.data));

I get this error: 我收到此错误:

在此处输入图片说明

Here is the raw data when logging to console 这是登录控制台时的原始数据

This is how I did it in our product. 这就是我在产品中所做的。 Please give it a try. 请试一试。

Essentially the data you're getting back is Uint8Array . 本质上,您要获取的数据是Uint8Array First thing you would need to do is convert that array into string. 您需要做的第一件事是将该数组转换为字符串。 You can use the following code to do so: 您可以使用以下代码进行操作:

function Uint8ToString(array) {
    var chunkSize = 0x8000;
    var c = [];
    for (var i = 0; i < array.length; i += chunkSize) {
        c.push(String.fromCharCode.apply(null, array.subarray(i, i + chunkSize)));
    }
    return c.join('');
}

Next, you need to convert this string in base64 format. 接下来,您需要将该字符串转换为base64格式。 Here's how I'm doing it currently: 这是我目前的操作方式:

var blobContentsAsString = Uint8ToString(blobContents); 
var blobContentsAsBase64String = btoa(blobContentsAsString);
$scope.camera.imageUrl = "data:image/jpeg;base64," + blobContentsAsBase64String;

Do give it a try. 尝试一下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM