簡體   English   中英

將從URL提取的圖像轉換為base64

[英]Convert image extracted from URL to base64

每當他們通過Facebook登錄時,我都會獲取用戶的Facebook個人資料照片。 我想將圖像從URL轉換為base 64。 在確保用戶仍然可以在視圖(home.view)中看到其個人資料圖片的同時,這樣做的最佳方法是什么? 此刻,我直接指的是URL。

到目前為止,這是我的代碼:

facebook.service.js

function FacebookService($http, config) {
      this.getUserPicture = function(userId, token) {
      return $http({
        method: 'GET',
        url: 'https://graph.facebook.com/' + userId + '/picture?type=large&redirect=false'
      })
    }
  }

home.controller.js

function HomeController($scope, $cordovaNativeStorage, FacebookService, $ionicLoading) {
  if (window.cordova) {
    // Get Facebook access token
    $cordovaNativeStorage.getItem("facebookAccessToken").then(function(value) {
      $scope.facebookAccessToken = value

      // Get Facebook user picture (currently stored as a URL, would want to store it as a base 64 string which can be displayed as an image
      FacebookService.getUserPicture($scope.facebookUserData.id).then(function(dataResponse) {
        $scope.facebookUserPicture = dataResponse.data;

        // Save Facebook user picture
        $cordovaNativeStorage.setItem("facebookUserPicture", $scope.facebookUserPicture).then(function() {}, function(error) {
          console.error("Unable to cache user data: " + result);
          $ionicLoading.show({
            template: 'Unable to cache user data',
            duration: 1500
          })
        });
      }, function(error) {
        console.log(error.data.error.message)
      })
    }, function(error) {
      console.log(error.data.error.message)
    })
  }
};

home.view.js

<img class="icon icon-home img-circle" ng-src="{{ facebookUserPicture.data.url }}">

有一種方法可以通過canvas( source )完成:

var convertImgToDataURLviaCanvas = function(url, callback) {
  var img = new Image();

  img.crossOrigin = 'Anonymous';

  img.onload = function() {
    var canvas = document.createElement('CANVAS');
    var ctx = canvas.getContext('2d');
    var dataURL;
    canvas.height = this.height;
    canvas.width = this.width;
    ctx.drawImage(this, 0, 0);
    dataURL = canvas.toDataURL();
    callback(dataURL);
    canvas = null;
  };

  img.src = url;
}

convertImgToDataURLviaCanvas( 'http://some.com/images/1.jpg', function( base64_data ) {
    console.log( base64_data );
} );

您可以使用此輔助函數來獲取URL並將其轉換為dataURI。

function getDataUri(url, callback) {
var image = new Image();

image.onload = function () {
    var canvas = document.createElement('canvas');
    canvas.width = this.naturalWidth; // or 'width' if you want a special/scaled size
    canvas.height = this.naturalHeight; // or 'height' if you want a special/scaled size

    canvas.getContext('2d').drawImage(this, 0, 0);

    // Get raw image data
    callback(canvas.toDataURL('image/png').replace(/^data:image\/(png|jpg);base64,/, ''));

    // ... or get as Data URI
    callback(canvas.toDataURL('image/png'));
};

image.src = url;
}

用法:

getDataUri($scope.facebookUserPicture.url, function(dataUri) {

 // here you can set it up as the img src for the profile picture
  $scope.profilePictureUri = dataUri;

});

您也可以將其定義為承諾而不是回叫。

最后, <img class="icon icon-home img-circle" ng-src="{{profilePictureUri}}">

閱讀有關David Walash的精彩文章的更多信息

這將以blob的形式獲取任何資源,並使用filereader將其轉換為base64數據url。 如果您在哪里使用canvas#toDataURL,則不會獲得相同的base64 ...

 var blob = new Blob(['Simulate a url']) var url = URL.createObjectURL(blob) console.log("original blob size", blob.size) fetch(url) .then(res => res.blob()) .then(blob => { var fr = new FileReader() fr.onload = () => { var b64 = fr.result console.log(b64) console.log("base64 size: ", b64.length) $iframe.src = b64 } fr.readAsDataURL(blob) }) 
 <iframe id="$iframe"></iframe> 


有更好的方法來解決此問題,也就是將以某種方式獲取的原始二進制文件存儲為Blob。 Base64將占用約3倍的數據,並且由於javascript字符串是utf16,因此它將占用2倍的內存...

一些好的替代方法是indexedDB和Sandboxed Filesystem API

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM