Search code examples
javascripthtmlimagedata-uri

Img url to dataurl using JavaScript


Using JavaScript, I want to convert an img tag like this:

<img width="11" height="14" src="http://mysite/file.gif" alt="File Icon">

Into one with a dataurl like this:

<img width="11" height="14" src="data:image/gif;base64,R0lGODlhCwAOAMQfAP////7+/vj4+Hh4eHd3d/v7+/Dw8HV1dfLy8ubm5vX19e3t7fr6+nl5edra2nZ2dnx8fMHBwYODg/b29np6eujo6JGRkeHh4eTk5LCwsN3d3dfX13Jycp2dnevr6////yH5BAEAAB8ALAAAAAALAA4AAAVq4NFw1DNAX/o9imAsBtKpxKRd1+YEWUoIiUoiEWEAApIDMLGoRCyWiKThenkwDgeGMiggDLEXQkDoThCKNLpQDgjeAsY7MHgECgx8YR8oHwNHfwADBACGh4EDA4iGAYAEBAcQIg0Dk gcEIQA7" alt="File Icon">

Is this possible?


Solution

  • First, load the image into a canvas

    var canvas = document.createElement("canvas");
    context = canvas.getContext('2d');
    
    make_base();
    
    function make_base()
    {
      base_image = new Image();
      base_image.src = 'img/base.png';
      base_image.onload = function(){
        context.drawImage(base_image, 100, 100);
      }
    }
    

    Make sure to update the context.drawImage(base_image, 100, 100); to values appropriate for your application.

    Source: https://stackoverflow.com/a/6011402/3969707

    Then convert the canvas to data.

    var jpegUrl = canvas.toDataURL("image/jpeg");
    var pngUrl = canvas.toDataURL(); // PNG is the default
    

    Source: https://stackoverflow.com/a/15685877/3969707