Promisified createImageBitmap()

During the “work” (read HAVING FUN) on my side project I often need to reuse some of my older code. As a side effect I am building my own library of utility functions, some of which I occasionaly publish. Such as this one. I am sure it will be handy for my future self, and quite likely for you as well. Feel free to use it as you wish, live long and prosper!

Related readingHow to load Image programaticaly using Promise.

/**
 * Returns Promise which resolves when ImageBitmap was extracted from the Image
 */
export function readImageBitmap(file: File): Promise<ImageBitmap> {
  const promise: Promise<ImageBitmap> = new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onloadend = () => {
      const image = new Image();
      image.onload = () => {
        createImageBitmap(image).then((bitmap: ImageBitmap) => {
          resolve(bitmap);
        });
      }
      image.onerror = (err) => {
        console.error('[readImageBitmap] Could not read image', err);
        reject(err);
      }
      image.src = (reader.result as string);
    }

    reader.readAsDataURL(file);
  })

  return promise;
}