Search code examples
javascripthtmldownloadpngblob

Creating and saving to file new png image in JavaScript


I am trying to create new empty image with width and height and save it as png to file.

This is what i got:

var myImage = new Image(200, 200);
myImage.src = 'picture.png';


window.URL = window.webkitURL || window.URL;

var contentType = 'image/png';

var pngFile = new Blob([myImage], {type: contentType});

var a = document.createElement('a');
a.download = 'my.png';
a.href = window.URL.createObjectURL(pngFile);
a.textContent = 'Download PNG';

a.dataset.downloadurl = [contentType, a.download, a.href].join(':');

document.body.appendChild(a);

I am trying to get transparent image with given width and height in var myImage new Image(200, 200) as the output on the download.


Solution

  • The Image element can only load an existing image. To create a new image you will have to use canvas:

    var canvas = document.createElement("canvas");
    
    // set desired size of transparent image
    canvas.width = 200;
    canvas.height = 200;
    
    // extract as new image (data-uri)
    var url = canvas.toDataURL();
    

    Now you can set url as href source for the a-link. You can specify a mime-type but without any it will always default to PNG.

    You can also extract as blob using:

    // note: this is a asynchronous call
    canvas.toBlob(function(blob) {
      var url = (URL || webkitURL).createObjectURL(blob);
      // use url here..
    });
    

    Just be aware of that IE does not support toBlob() and will need a polyfill, or you can use navigator.msSaveBlob() (IE does neither support the download attribute so this will kill two birds with one stone in the case of IE).