-1

I am trying to convert my attached image into base64 .I tried like this, but getting error .

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

    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, 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(){
 // alert()
  $('#fileId').on('change', function (e) {
            console.log('ddd');
            var file = e.target.files[0];
            console.log(getBase64Image(file))
        })
})

i attached one png value

it is not printing the base64 value

user944513
  • 12,247
  • 49
  • 168
  • 318
  • 1
    Possible duplicate of [Uncaught TypeError when calling drawImage function](https://stackoverflow.com/questions/31457605/uncaught-typeerror-when-calling-drawimage-function) – tao Aug 17 '18 at 02:06
  • 1
    @AndreiGheorghiu too complicated - there's no need for a server round trip for this. – We Are All Monica Aug 17 '18 at 02:12
  • @user944513 thanks for including a jsbin link, that helps, and in the future it also helps to include the exact error message with your questions. – We Are All Monica Aug 17 '18 at 02:13

1 Answers1

1

When I run this code, I get the following error:

TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLImageElement or SVGImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap or OffscreenCanvas)'

So a File object like e.target.files[0] won't work. We need to convert it into an HTMLImageElement first. Here is how to do that (from another answer):

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]);     
}

Now you have a HTMLImageElement. However, you really don't need it, or the canvas at all: event.target.result from the FileReader is already a data: URL like you want.

We Are All Monica
  • 13,000
  • 8
  • 46
  • 72