Javascript 无法读取属性';宽度';将图像转换为base64时的未定义属性?
我想将图像转换为Javascript 无法读取属性';宽度';将图像转换为base64时的未定义属性?,javascript,jquery,Javascript,Jquery,我想将图像转换为base64格式并发送到服务器。我试图转换图像base64,但出现此错误 无法读取未定义函数的属性“宽度” getBase64Image(img) { // Create an empty canvas element var canvas = document.createElement("canvas"); canvas.width = img.width; canvas.heig
base64
格式并发送到服务器。我试图转换图像base64,但出现此错误
无法读取未定义函数的属性“宽度”
getBase64Image(img) {
// Create an empty canvas element
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
// Copy the image contents to the canvas
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
// Get the data-URL formatted image
// Firefox supports PNG and JPEG. You could check img.src to
// guess the original format, but be aware the using "image/jpg"
// will re-encode the image.
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
function handleImage(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img,0,0);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
$(function(){
// alert()
$('#fileId').on('change', function (e) {
console.log('ddd');
var file = e.target.files[0];
console.log(getBase64Image(handleImage(e)))
})
})
here is my code
我附加了一个图像,并试图获得base64字符串,然后我得到了这个错误
从handleImage()
函数返回一些值
函数handleImage()
不返回任何值。因此,当您在代码的最后几行中执行console.log(getBase64Image(handleImage(e))
时,不会有任何内容作为函数getBase64Image()
的参数传入。因此,函数getBase64Image()
中img
的值是undefined
,因此当您试图读取代码第三行img
未定义的img.width
时,会出现错误无法读取undefined
的属性“width”。请检查此项
我在这里所做的基本上是从文件url创建一个图像,并在画布上绘制该图像,其余部分是您的代码
function getBase64Image(img) {
// Create an empty canvas element
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
// Copy the image contents to the canvas
var ctx = canvas.getContext("2d");
ctx.drawImage(img, img.width, img.height);
// Get the data-URL formatted image
// Firefox supports PNG and JPEG. You could check img.src to
// guess the original format, but be aware the using "image/jpg"
// will re-encode the image.
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
function handleImage(e, callback) {
var img = new Image();
img.onload = function(event) {
let r = getBase64Image(img);
callback(r);
};
img.src = URL.createObjectURL(e.target.files[0]);
}
$(function() {
// alert()
$('#fileId').on('change', function(e) {
var file = e.target.files[0];
handleImage(e, function(r) {
console.log(r);
});
})
})
您正在
getBase64Image
中定义canvas
,但是您正在尝试在handleImage
中使用它,而它似乎不在范围内。您能建议我将图像转换为base64
并发送到服务器的最佳方式吗?他们将在db
上保存。请遵循此链接,您能建议我如何获得base64
stringWell,我对此一无所知。你应该创建另一个帖子来获得你这个问题的答案。但是,你得到的bug是因为我告诉你的原因。:)