Skip to content

Instantly share code, notes, and snippets.

@akbarjondev
Last active October 28, 2023 11:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akbarjondev/3a17f9cb670508151ad2559232cadf22 to your computer and use it in GitHub Desktop.
Save akbarjondev/3a17f9cb670508151ad2559232cadf22 to your computer and use it in GitHub Desktop.
Hook for converting small images or thumbnails into binary data. Converting images in this way gives good experience while loading images in Next.js apps
import { useEffect } from 'react'
export function useImageToBase64(
src: string,
callback: (res: string) => void,
outputFormat?: string
) {
useEffect(() => {
let img = new Image() // Image constructor equivalent to document.createElement
img.crossOrigin = 'Anonymous'
img.onload = function () {
let canvas = document.createElement('CANVAS')
let ctx = canvas.getContext('2d')
let dataURL
canvas.height = this.naturalHeight
canvas.width = this.naturalWidth
ctx.drawImage(this, 0, 0)
dataURL = canvas.toDataURL(outputFormat)
callback(dataURL)
}
img.src = src
if (img.complete || img.complete === undefined) {
img.src =
'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=='
img.src = src
}
}, [])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment