Create a FileReader()
object and use readAsDataURL()
function to read an image and transform it into base64:
jsximport React, { useState } from 'react'; const Upload = () => { const [src, setSrc] = useState(null); const uploadPic = (e) => { let file = e.target.files[0]; let reader = new FileReader(); reader.readAsDataURL(file); reader.onload = () => setSrc(reader.result); } return( <div className = 'Upload'> <input type = 'file' onChange = {uploadPic} accept = 'image/*'/> <img src = {src}/> </div> ); } export default Upload;
accept = 'image/*'
to accept only images.Example:
javascriptconst resizeMe = (img, maxWidth) => { let canvas = document.getElementById('background'); let ctx = canvas.getContext('2d'); canvas.width = maxWidth; canvas.height = maxWidth * (img.height/img.width); ctx.drawImage(img, 0, 0, canvas.width, canvas.height); return canvas.toDataURL("image/jpeg", 0.7); }
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.