将Canvas转换为带有src blob的img

6

我正在从画布中创建一个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,像这样:

//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 是如何定义的? - Igwe Kalu
2个回答

6

我刚刚找到了一个解决方案,使用了这个问题的答案:将Data URI转换为文件,然后附加到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});
}

只是想进来说一声,与此同时<canvas>有一个toBlob()方法可能会有所帮助。 - Surma

3

使用toBlob方法,从IE>=10就可以轻松解决此问题。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接