logo
post image

Resize Image in React Before Upload

While uploading an image, sometimes it may be required to resize it on the client side and sending the resized image to the server. The <canvas> element is a good way to resize client side images without using server side resources.

'use client'

export default function FileResize() {
  async function imageResize() {
    const originalImage = document.querySelector("[name='file']").files?.[0]

    const previewURL = URL.createObjectURL(originalImage)
    const img = new Image()
    img.src = previewURL
    await img.decode()

    // resize image to 300 x 300
    const offscreenResize = new OffscreenCanvas(300, 300)
    const offscreenResizeContext = offscreenResize.getContext("2d")
    offscreenResizeContext.drawImage(img, 0, 0, 300, 300)

    // resized image blob
    // this can be sent to server
    const resizedImage = await offscreenResize.convertToBlob({ type: 'image/jpeg', quality: 0.8 })

    // clear object url
    URL.revokeObjectURL(previewURL)
  }

  return (
    <>
      <input type="file" name="file" />
      <button onClick={imageResize}>Resize</button>
    </>
  )
}

We are using an OffscreenCanvas since we just need to resize the image and use it rather than rendering the canvas on the page. OffscreenCanvas is a better way of doing this as computation is done on an alternative asynchronous thread and not on the main thread.