Creating and saving to file new png image in JavaScript

三世轮回 提交于 2021-02-08 03:42:46

问题


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.


回答1:


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).




回答2:


Thank you K3N for replying to my question but i did not have time to wrap my head around your answer.

Your answer was just what i needed!

Here is what i got:

var canvas = document.createElement("canvas");

canvas.width = 200;
canvas.height = 200;

var url = canvas.toDataURL();

var a = document.createElement('a');
a.download = 'my.png';
a.href = url;
a.textContent = 'Download PNG';



document.body.appendChild(a);


来源:https://stackoverflow.com/questions/42932645/creating-and-saving-to-file-new-png-image-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!