【问题标题】:Canvas to img with src blob使用 src blob 到 img 的画布
【发布时间】:2015-02-09 16:33:55
【问题描述】:

我正在从画布创建 PNG 文件,但在我想将画布显示为 img 元素之前,使用 blob 作为 img 的 src。到目前为止我尝试了什么:

canvas = document.getElementById("canvas");
//Get data from canvas
img_b64 = canvas.toDataURL('image/png');
//Create PNG
png = img_b64.split(',')[1];
//Create new img
img = document.createElement("img");
img.src = img_b64;
//Append img to document
//Save png

这可行,但我想要一个 blob 作为 img 的 src 而不是 img_b64,如下所示:

//Create blob from new PNG
blob = new Blob([window.atob(png)], { type: 'image/png', encoding: 'utf-8' });
//Create new img with blob as src
img = document.createElement("img");
img.src = URL.createObjectURL(blob);
//Append img to document
//Save png

上面的代码只显示了一个空的img。有没有办法做到这一点,还是我必须先创建 png 文件,然后再为其创建一个 blob?

【问题讨论】:

  • 查看blob = new Blob([window.atob(png)]...,该语句中的png 是如何定义的?

标签: javascript canvas png blob


【解决方案1】:

我刚刚使用这个问题的答案找到了一个解决方案:Convert Data URI to File then append to FormData。使用dataURItoBlob 函数我的代码是:

canvas = document.getElementById("canvas");
//Get data from canvas
img_b64 = canvas.toDataURL('image/png');
//Create blob from DataURL
blob = dataURItoBlob(img_b64)
img = document.createElement("img");
img.src = URL.createObjectURL(blob);
//Insert image

dataURItoBlob 函数:

function dataURItoBlob(dataURI) {
    // convert base64/URLEncoded data component to raw binary data held in a string
    var byteString;
    if (dataURI.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(dataURI.split(',')[1]);
    else
        byteString = unescape(dataURI.split(',')[1]);

    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

    // write the bytes of the string to a typed array
    var ia = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    return new Blob([ia], {type:mimeString});
}

【讨论】:

  • 只是想顺便说一下,与此同时&lt;canvas&gt; 得到了一个可能有用的toBlob() 方法。
【解决方案2】:

使用toBlob,这应该很容易从 IE>=10 解决。

  const img = document.createElement("img");
  canvas.toBlob((blob) => {
    img.src =  URL.createObjectURL(blob);
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-04
    • 1970-01-01
    • 2012-08-28
    • 1970-01-01
    • 2017-10-17
    • 1970-01-01
    • 2020-04-29
    • 2016-12-13
    相关资源
    最近更新 更多