I'm using createImageBitmap() which creates an ImageBitmap file.
How do I convert this file to a blob or ideally PNG so I can upload?
The only way currently is to draw it on a canvas.
For more efficiency, you can try to use an ImageBitmapRenderingContext, which will not copy the pixels buffer again.
(async () => {
const resp = await fetch('https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png');
// yes.. from a Blob to a Blob...
const blob1 = await resp.blob();
const bmp = await createImageBitmap(blob1);
console.log(bmp); // ImageBitmap
// create a canvas
const canvas = document.createElement('canvas');
// resize it to the size of our ImageBitmap
canvas.width = bmp.width;
canvas.height = bmp.height;
// get a bitmaprenderer context
const ctx = canvas.getContext('bitmaprenderer');
ctx.transferFromImageBitmap(bmp);
// get it back as a Blob
const blob2 = await new Promise((res) => canvas.toBlob(res));
console.log(blob2); // Blob
const img = document.body.appendChild(new Image());
img.src = URL.createObjectURL(blob2);
})().catch(console.error);
Check HTMLCanvasElement#toBlob() for the options you can pass in (file format and quality when applicable).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With