newbie newbie - 1 month ago 9x
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');

Error that I got from firbug console:

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

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.


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