javascript - 使用 src blob Canvas 到 img

标签 javascript canvas png blob

我正在从 Canvas 创建 PNG 文件,但在我想将 Canvas 显示为 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?

最佳答案

我刚刚使用这个问题的答案找到了解决方案: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});
}

关于javascript - 使用 src blob Canvas 到 img,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27418672/

相关文章:

javascript - 在 Promise.catch 中调用函数是未定义的

Javascript 将日期传递给 MVC Controller

javascript - 如何在 Highcharts 中定位 Axis 标签

javascript - JS Canvas-将图像数据放入 Alpha 中?

ios - SpriteKit 背景 PNG,Alpha 显示黑色

javascript - 如何使用javascript随机决定两个数字?

javascript - 我的 Web 应用程序的 Canvas 绘图

image - 通过 websocket 发送一个 png 图像并渲染接收到的图像

iphone - 为通用应用程序压缩图像

javascript - 如何调整 Canvas 大小以适合浏览器窗口?