【问题标题】:Creating and saving to file new png image in JavaScript在 JavaScript 中创建并保存到文件新的 png 图像
【发布时间】:2017-08-13 10:41:37
【问题描述】:

我正在尝试创建具有宽度和高度的新空图像并将其保存为 png 到文件。

这是我得到的:

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

我正在尝试在var myImage new Image(200, 200) 中获取具有给定宽度和高度的透明图像作为下载的输出。

【问题讨论】:

    标签: javascript html download png blob


    【解决方案1】:

    Image 元素只能加载现有图像。要创建新图像,您必须使用画布:

    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();
    

    现在您可以将 url 设置为 a-link 的 href 源。你可以指定一个mime-type,但没有任何它总是默认为PNG。

    您还可以使用以下方法提取为 blob:

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

    请注意,IE 不支持toBlob(),需要polyfill,或者您可以使用navigator.msSaveBlob()(IE 不支持download 属性,所以这会用一块石头杀死两只鸟IE的情况)。

    【讨论】:

      【解决方案2】:

      感谢 K3N 回复我的问题,但我没有时间思考您的回答。

      你的回答正是我需要的!

      这是我得到的:

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

      【讨论】:

        猜你喜欢
        • 2018-10-13
        • 1970-01-01
        • 2016-04-22
        • 2020-10-12
        • 2010-10-24
        • 2016-12-01
        • 1970-01-01
        • 2014-04-26
        • 2020-10-24
        相关资源
        最近更新 更多