0
我想獲取並轉換我的圖像到Base64,但編碼(沒有任何可能粉碎我的應用程序的特殊字符)。可悲的是,代碼無法正常工作。我想知道代碼是否有問題。如何正確地將圖像轉換爲Base64?
下面是代碼:
$('#button_upload').on('click', function() {
upload();
});
$(":file").on('change', function(){
loadImage(this);
});
function isBase64(str) {
try {
return btoa(atob(str)) == str;
}catch (err) {
return false;
}
}
function getDataUri(url, callback) {
var image = new Image();
image.onload = function (url) {
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);
callback(canvas.toDataURL('image/jpeg').replace(/^data:image\/(png|jpg);base64,/, ''));
};
image.src = url;
};
function loadImage(image) {
if (image.files && image.files[0]) {
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(image.files[0]);
};
};
function imageIsLoaded(e) {
$('#myImg').attr('src', e.target.result);
};
function upload() {
var src = document.getElementById('myImg').src
getDataUri(src, function (dataUri) {
var parameters= {
picture: dataUri
};