无法读取未定义的Whille将图像转换为base64的属性“ width”?

时间:2018-08-17 04:42:39

标签: javascript jquery

我想将图像转换为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

https://jsbin.com/zagagivuje/edit?html,js,console,output

我附加了一张图像并尝试获取base64字符串,然后出现此错误

2 个答案:

答案 0 :(得分:0)

  

从您的handleImage()函数返回一些值。

您的函数handleImage()不返回任何值。因此,当您在代码的最后几行中执行console.log(getBase64Image(handleImage(e)))时,不会传递任何内容作为函数getBase64Image()的参数。因此,函数imggetBase64Image()的值为undefined,因此,当您尝试在函数的第三行读取Cannot read property 'width' of undefined时,会得到错误img.width。您的未定义img的代码。

答案 1 :(得分:0)

签出此link

我在这里所做的基本上是从文件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);
    });
  })
})