从Base64 Ionic编码和解码图像

时间:2022-12-02 23:58:42

I am making an app (ionic) that upload images as a string to some online service, I only have the URI of the image on the device, how can I load the image and convert it to base64 string, and later view it in the app?

我正在制作一个应用程序(离子),将图像作为字符串上传到某个在线服务,我只有设备上的图像的URI,我如何加载图像并将其转换为base64字符串,然后在应用程序吗?

1 个解决方案

#1


0  

Use FileReader:

The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read.

FileReader对象允许Web应用程序异步读取存储在用户计算机上的文件(或原始数据缓冲区)的内容,使用File或Blob对象指定要读取的文件或数据。

By create function:

通过创建功能:

function convertFileToDataURLviaFileReader(url, callback){
    var xhr = new XMLHttpRequest();
    xhr.responseType = 'blob';
    xhr.onload = function() {
        var reader  = new FileReader();
        reader.onloadend = function () {
            callback(reader.result);
        }
        reader.readAsDataURL(xhr.response);
    };
    xhr.open('GET', url);
    xhr.send();
}

Then call it to get base64 data:

然后调用它来获取base64数据:

convertFileToDataURLviaFileReader('yourUrlHere',function(base64Data){
    //do something with base64Date

    //show image
    $scope.imageSrc=base64Data;
});

With markup:

<image ng-src="imageSrc" />

#1


0  

Use FileReader:

The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read.

FileReader对象允许Web应用程序异步读取存储在用户计算机上的文件(或原始数据缓冲区)的内容,使用File或Blob对象指定要读取的文件或数据。

By create function:

通过创建功能:

function convertFileToDataURLviaFileReader(url, callback){
    var xhr = new XMLHttpRequest();
    xhr.responseType = 'blob';
    xhr.onload = function() {
        var reader  = new FileReader();
        reader.onloadend = function () {
            callback(reader.result);
        }
        reader.readAsDataURL(xhr.response);
    };
    xhr.open('GET', url);
    xhr.send();
}

Then call it to get base64 data:

然后调用它来获取base64数据:

convertFileToDataURLviaFileReader('yourUrlHere',function(base64Data){
    //do something with base64Date

    //show image
    $scope.imageSrc=base64Data;
});

With markup:

<image ng-src="imageSrc" />