newbie newbie - 1 year ago 143
jQuery Question

How to convert pre-loaded image into base64 data in jQuery

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.

K3N K3N
Answer Source

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