0

I am referring to Get image data in JavaScript?

Using jQuery, I wanted convert pre-loaded img into base64 encoded data. I tried the function I found at mentioned url in following way which gave me errors.

Function that I found from mentioned link:

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,/, "");
}

How I tried it:

var a = $('[active_contact][serial=1] img');
console.log(get_base64_image(a));

Error that I got from firbug console:

TypeError: Argument 1 of CanvasRenderingContext2D.drawImage could not be converted to any of: HTMLImageElement, HTMLCanvasElement, HTMLVideoElement.
get_base64_image()

ctx.drawImage(img, 0, 0);

How can I get this thing worked? I want to use jQuery to convert the pre-loaded images into base64 to reuse. Any better ideas are welcome.

Community
  • 1
  • 1
newbie
  • 27
  • 6

2 Answers2

1

Make sure you pass in the actual Image element (and that it has been properly loaded):

var a = $('[active_contact][serial=1] img')[0]; // notice [0] at the end = image
0

Your function names don't match.

In the def. it's getBase64Image while when you calling it you wrote get_base64_image.

I was looking for some code like this and yours worked for me after changing the name.

d-coder
  • 1,180
  • 1
  • 11
  • 17