gpt4 book ai didi

javascript - 将从 URL 提取的图像转换为 base64

转载 作者:行者123 更新时间:2023-11-29 16:46:21 25 4
gpt4 key购买 nike

每当用户通过 Facebook 登录时,我都会获取他们的 Facebook 个人资料图片。我想将图像从 URL 转换为 base 64。这样做的最佳方式是什么,同时确保用户仍然可以在 View (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 );
} );

关于javascript - 将从 URL 提取的图像转换为 base64,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40947200/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com