[英]How Do I convert my Image to Base64 correctly?
I am trying to get and convert my image to Base64 but encoded (free of any special characters that could crush my application). 我正在尝试将图像转换为Base64并进行编码(没有任何可能损坏我的应用程序的特殊字符)。 Sadly, the code is not working.
可悲的是,该代码无法正常工作。 I wonder if there is something wrong with the code.
我想知道代码是否有问题。
Here is the code: 这是代码:
$('#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
};
I fixed that in the line: 我将其固定在行中:
FROM 从
callback(canvas.toDataURL('image/jpeg').replace(/^data:image\/(png|jpg);base64,/, ''));
TO 至
callback(canvas.toDataURL('image/jpeg').replace(/^data:image\/(png|jpeg);base64,/, ''));
It is String literals, so the regular expression must be EXACTLY equal to the situation. 它是String文字,因此正则表达式必须与情况完全相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.