Friday Knowledge
Published in

Friday Knowledge

Image Preview made easy

Leveraging createImageBitmap to create image previews

In Google I/O 2022, the web team announced that most major browsers now have implemented createImageBitmap api.

So, we will look at one feature that used to require too much effort to achieve, and how we can easily implement this feature with the help of createimageBitmap.

Use case

This payment tracking app, allows users to upload receipts of share payments, so that they can later reference it, if someone who owes them ask them how much they should pay back.

When users pick the receipt image, the app shows them a preview before they can submit the receipt.

Screenshot of New payment entry inside PaidFor app

Without createImageBitmap

When this feature was added, createImageBitmap was not a thing. Therefore, we chose a more complex implantation that relies on multiple apis

createObjectURL to generate a url like reference

fetch to get both buffer and blob from the url we generate above

We then user blob and buffer to generate a base64 version of the receipt image that we can display using an image tag.

Below is the complete code

NOTE that we have to cleanup after we are done generating the base64 url, in order to prevent possible memory leaks.

We do this by calling revokeObjectURL

With createImageBitmap

Now, look at an implementation that uses createImageBitmap and displays the image using canvas tag

There are a few benefits that stand out

  • First, we have less code, which is always good from a maintenance point of view.
  • Second, we no longer have to remember to clean up.
  • Third, well I will leave this one for you!

Overall, it is good to see how the web platform keeps helping web developers deliver good experiences.




Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Marcellin Nshimiyimana

Marcellin Nshimiyimana

Always debugging, because problem knowledge equals half the solution!