2017-04-24 130 views
-1

看看我的代码如何将png图像字符串数据转换为png?

<img src='data:image/png;base64,{{imgSrc}}'> 

在我的控制器

$scope.imgSrc = $scope.deviceDetail.imgSrc; 

我得到这个类型从我IMGSRC后端存储在MongoDB的响应。

"�PNG\r\n\u001a\n\u0000\u0000\u0000\rIHDR\u0000\u0000\u0003 \u0000\u0000\u0002R\b\u0002\u0000\u0000\u0000��6A\u0000\u0000\u0000\u0006bKGD\u0000�\u0000�\u0000�����\u0000\u0000 \u0000IDATx���{xT���W x\u0000\u0006%$F�c F\t�\"�V��\u0000�P\u000f\b���xEъ��T�[email protected]� \u0018�諀`�TJ�Z\u0015\t�\"R��@\u000b|H�h8\u0005\......" 

现在我想从这个数据的png图像,我已经试过这个数据到base64,但仍然没有得到图像。 请问我这里有什么问题?

+0

你是如何保存在数据库中这一形象。将图像存储为base64编码的字符串而不是二进制。 – Thangadurai

+0

检查这个帖子,它可能会帮助你。 http://stackoverflow.com/questions/4796914/store-images-in-a-mongo-database – CrazyMac

+0

@Thangadurai我从ubersmithAPI服务器获取这个图像数据,并在mongodb中存档,我试过这个数据到base64,但它返回此错误 错误:路径必须是不含空字节的字符串。 –

回答

0

您可以将图像转换为数据base64位。

Base64是一组类似的二进制到文本编码方案,它们将ASCII码字符串格式的二进制数据转换成基数为64的表示形式,代表 。

要用cordova,ionic或phonegap将文件转换为base64(图像或任何其他类型的文件),我们将只需要cordova文件插件和1个人眼。然后我们将使用FileReader通过readAsDataURL方法读取文件的内容。

/** 
* This function will handle the conversion from a file to base64 format 
* 
* @path string 
* @callback function receives as first parameter the content of the image 
*/ 
function getFileContentAsBase64(path,callback){ 
    window.resolveLocalFileSystemURL(path, gotFile, fail); 

    function fail(e) { 
      alert('Cannot found requested file'); 
    } 

    function gotFile(fileEntry) { 
      fileEntry.file(function(file) { 
       var reader = new FileReader(); 
       reader.onloadend = function(e) { 
        var content = this.result; 
        callback(content); 
       }; 
       // The most important point, use the readAsDatURL Method from the file plugin 
       reader.readAsDataURL(file); 
      }); 
    }} 

然后,我们将用它来本地图像转换为Base64: VAR路径= “文件://storage/0/downloads/myimage.png”;

// Convert image 
getFileContentAsBase64(path,function(base64Image){ 
    //window.open(base64Image); 
    console.log(base64Image); 
    // Then you'll be able to handle the myimage.png file as base64 
}); 

记住,你需要从科尔多瓦文件的插件,阅读和学习如何在这里使用它。您可以在科尔多瓦CLI执行文件下载插件到您的项目:

cordova plugin add cordova-plugin-file 

继续here

https://gist.github.com/HereChen/e173c64090bea2e2fa51

http://tutsheap.com/web/javascript/get-base64-image-url/