【发布时间】:2019-03-28 07:53:07
【问题描述】:
我正在使用 createImageBitmap() 创建一个ImageBitmap 文件。
如何将此文件转换为 blob 或最好的 PNG 格式以便上传?
【问题讨论】:
-
我对我的答案进行了编辑,以使其使用位图渲染器上下文。在第一个版本中没有提及它是愚蠢的......
标签: javascript image html5-canvas
我正在使用 createImageBitmap() 创建一个ImageBitmap 文件。
如何将此文件转换为 blob 或最好的 PNG 格式以便上传?
【问题讨论】:
标签: javascript image html5-canvas
目前唯一的方法是在画布上绘制它。
为了提高效率,您可以尝试使用ImageBitmapRenderingContext,这将不会再次复制像素缓冲区。
重要说明关于位图渲染器的使用:
虽然这确实是最佳实践,Chrome currently has a bug 会导致输出图像是透明的,从而迫使我们改用 2d 上下文。
我保留了使用 bitmaprenderer 上下文的代码,但希望这个 bug 能很快得到修复,但这意味着下面的 sn-p 暂时只能在 FF 上工作。
fetch('https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png')
.then(r => r.blob()) // yes.. from a Blob to a Blob...
// ImageBitmap generation
.then(createImageBitmap)
// to Blob
.then(img => {
console.log(img); // ImageBitmap
return new Promise(res => {
// create a canvas
const canvas = document.createElement('canvas');
// resize it to the size of our ImageBitmap
canvas.width = img.width;
canvas.height = img.height;
// try to get a bitmaprenderer context
let ctx = canvas.getContext('bitmaprenderer');
if(ctx) {
// transfer the ImageBitmap to it
ctx.transferFromImageBitmap(img);
}
else {
// in case someone supports createImageBitmap only
// twice in memory...
canvas.getContext('2d').drawImage(img,0,0);
}
// get it back as a Blob
canvas.toBlob(res);
});
})
.then(blob => {
console.log(blob); // Blob
var img = document.body.appendChild(new Image());
img.src = URL.createObjectURL(blob);
});
检查HTMLCanvasElement#toBlob() 了解您可以传入的选项(文件格式和质量,如果适用)。
【讨论】: