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
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
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.
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
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.
- Sample demo showcasing both implementations.