Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download a image on div?

I append "chartdiv00" div as a image to the "imgChart1" div.

LoadImage = function(){
    var imgData = $('#chartdiv00').jqplotToImageStr({});
    var imgElem = $('<img/>').attr('src',imgData);
    $('#imgChart1').append(imgElem);
}

then what i want is to download the "imgChart1" div's image as a png or jpg by a button click. How could I do that ? Can I use the download attribute in HTML5 ? Then what is the URL of my image? If I can convert the image into dataURI I can dowaload it I think. Is there a way to convert this kind of image to dataURI ?

Thanks

like image 284
DilanG Avatar asked Dec 03 '25 12:12

DilanG


1 Answers

If you print the image into a canvas element, then you can use the canvas.toDataURL() to get the base64 representation of the image.

https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement

EDIT: Here is a quick and dirty way how to get a download link of the canvas as an image.

            var canvas = $('<canvas>')[0];
            var ctx = canvas.getContext('2d');

            ctx.fillStyle='#f00';
            ctx.fillRect(0,0, canvas.width,canvas.height);

            var link = $('<a>').attr({
                href : canvas.toDataURL(),
                download : 'imageName',
                target : '_blank'
            }).text('download link');

            $('#Content').append(link);

PS. Keep in mind, that because you are using the canvas as a buffer to get the base64 code of the image you do not actually have to append it to the DOM tree. Also the jQuery is not essential, the same logic would work in pure JS as well.

like image 181
Idra Avatar answered Dec 05 '25 01:12

Idra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!