Last active
October 28, 2023 11:21
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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