Image Masking in React
<Button variant="contained" component="label">
Upload Icon
<input
accept="image/*"
multiple
type="file"
hidden
onChange={(e: ChangeEvent<HTMLInputElement>): void => handleUploadIcon(e)}
/>
</Button>
First, we create an upload button that accepts all images and creates an input tag of type file.
const handleUploadIcon = (e: ChangeEvent<HTMLInputElement>) => {
setImgFile(e.target.files[0])
const imagePromise = e.target.files[0].arrayBuffer().then((buf) => {
return makeImage(buf, figure, borderColor)
})
imagePromise.then((resized) => {
const fileReader = new FileReader()
fileReader.readAsDataURL(resized)
fileReader.onload = (e) => {
const image = new Image()
image.src = e.target.result as string
image.onload = () => {
const base64Img = e.target.result as string
// //! Convert icon to hash
const hash = CryptoJS.SHA256(base64Img).toString()
const file = dataURLtoFile(base64Img, 'MaskedImage.png')
dispatch(setInfo(base64Img, 'base64Img'))
dispatch(setInfo(hash, 'Icon Added'))
setFile(file)
}
}
})
}
We use the makeImage
function to mask the image and the dataURLtoFile
function to create a file object.
4 minutes to read