日本語

Resize and Preview Images Before Upload in React

​​React​Canvas API,File API,Playwright,TypeScript

A selected image can be resized in the browser by loading it with createImageBitmap(), drawing it on a small canvas, and writing it out with toBlob(). If you turn the written Blob into a File, use it for the preview, and put it into FormData as is, the server receives only the resized image. This is useful when you want to compress an image before uploading it and make the data you send smaller.

Here I made resizeImage, which shrinks the longer side to 1280px or less, and ImageResizeForm, a form that uses it. On the React side, the thing to watch is how to handle a different image being selected before the resizing has finished.

Note

The test environment was Ubuntu 24.04, Node.js 22.22.0, and Chromium 153. I used react / react-dom 19.3.1, @types/react 19.3.0, typescript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0. I type-checked the .tsx file with tsc, transformed it with esbuild, and used Playwright to operate Chromium and select files. The images used for testing were not camera photos. I drew gradients, circles, and noise with Pillow. Below, I call the 4032×3024 image I made in place of a photo "the photo". I did not test Firefox, Safari, mobile browsers, or image formats other than JPEG and PNG, such as HEIC.

Selecting a 4032×3024 photo shows a preview at 1280×960, and sending it shows a Japanese-language success message (meaning "Sent"). Then selecting a PNG with a transparent background shows a preview with a white background, on a pale blue page.
The result of selecting an image and sending it twice (changed displays are highlighted in pink; the file picker button stays in English, as shown by the browser used for testing)

Resize with createImageBitmap and canvas, and output as JPEG

resizeImage takes a File, resizes it, and returns it as a JPEG File. It does not depend on React, so any component can call it.

ts
export type Resized = {
  file: File;
  width: number;
  height: number;
  sourceWidth: number;
  sourceHeight: number;
};

// Shrink so the longer side is at most maxSize, and return it as a JPEG File
export async function resizeImage(file: File, maxSize: number, quality = 0.8): Promise<Resized> {
  const bitmap = await createImageBitmap(file);
  const { width: sourceWidth, height: sourceHeight } = bitmap;
  // Do not enlarge small images
  const scale = Math.min(1, maxSize / Math.max(sourceWidth, sourceHeight));
  const width = Math.round(sourceWidth * scale);
  const height = Math.round(sourceHeight * scale);

  const canvas = document.createElement('canvas');
  canvas.width = width;
  canvas.height = height;
  const ctx = canvas.getContext('2d');
  if (!ctx) throw new Error('canvas が使えません');
  // JPEG cannot hold transparency, so fill with white first
  ctx.fillStyle = '#fff';
  ctx.fillRect(0, 0, width, height);
  ctx.drawImage(bitmap, 0, 0, width, height);
  bitmap.close();

  const blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, 'image/jpeg', quality));
  if (!blob) throw new Error('画像を書き出せませんでした');
  const name = file.name.replace(/\.[^.]+$/, '') + '.jpg';
  return {
    file: new File([blob], name, { type: 'image/jpeg' }),
    width,
    height,
    sourceWidth,
    sourceHeight,
  };
}

As described in MDN's createImageBitmap() page, you can pass a Blob to createImageBitmap(). A File is a kind of Blob, so you can pass the file selected with input as is. The result is returned as a Promise.

The scale is determined by fitting the longer side to maxSize. Math.min(1, …) is there so that an image that is already small is not enlarged. In testing, when I selected an 800×600 image, it was written out as a JPEG at the same size.

text
--- 3. Do not enlarge small images (800×600) ---
元の画像:800×600、82 KB
送信する画像:800×600、36 KB

toBlob() passes its result through a callback, so I wrapped it in a Promise. According to MDN's toBlob() page, the second argument specifies the format, and the third argument specifies the quality for JPEG or WebP as a value from 0 to 1. If the image cannot be created, null is passed to the callback.

toBlob() returns a Blob, which has no file name. If you give it a name and type with the File constructor, the server can receive the file name when it is sent. Here, the extension of the original name is replaced with .jpg.

A form that selects an image, resizes it, and previews it

ImageResizeForm is a form that resizes an image chosen with input type="file" using resizeImage, and shows a preview and its size. When the submit button is pressed, it puts the resized image into FormData and sends it to /upload.

tsx
import { useEffect, useState, type ChangeEvent, type FormEvent } from 'react';
import { resizeImage, type Resized } from './resizeImage';

const MAX_SIZE = 1280;

// Create a URL for display from the File, and release it when no longer used
function useObjectUrl(file: File | undefined) {
  const [url, setUrl] = useState<string>();
  useEffect(() => {
    if (!file) return;
    const objectUrl = URL.createObjectURL(file);
    setUrl(objectUrl);
    return () => {
      URL.revokeObjectURL(objectUrl);
      setUrl(undefined);
    };
  }, [file]);
  return url;
}

const kb = (bytes: number) => `${Math.round(bytes / 1024).toLocaleString()} KB`;

export function ImageResizeForm() {
  const [original, setOriginal] = useState<File>();
  const [resized, setResized] = useState<Resized>();
  const [error, setError] = useState('');
  const [message, setMessage] = useState('');
  const previewUrl = useObjectUrl(resized?.file);

  useEffect(() => {
    if (!original) return;
    let ignore = false;
    resizeImage(original, MAX_SIZE)
      .then((result) => {
        if (!ignore) setResized(result);
      })
      .catch(() => {
        if (!ignore) setError('この画像は読み込めませんでした');
      });
    // If another image is selected, do not use the previous image's result
    return () => {
      ignore = true;
    };
  }, [original]);

  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    setOriginal(e.target.files?.[0]);
    setResized(undefined);
    setError('');
    setMessage('');
  };

  const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    if (!resized) return;
    const body = new FormData();
    body.append('image', resized.file);
    const res = await fetch('/upload', { method: 'POST', body });
    setMessage(res.ok ? '送信しました' : `送信できませんでした(${res.status})`);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="image">画像を選ぶ</label>
      <input id="image" type="file" accept="image/*" onChange={handleChange} />
      {original && !resized && !error && <p>縮小しています…</p>}
      {error && <p role="alert">{error}</p>}
      {original && resized && previewUrl && (
        <figure>
          <img src={previewUrl} alt="送信する画像のプレビュー" width={resized.width} height={resized.height} />
          <figcaption>
            元の画像:{resized.sourceWidth}×{resized.sourceHeight}、{kb(original.size)}
            <br />
            送信する画像:{resized.width}×{resized.height}、{kb(resized.file.size)}
          </figcaption>
        </figure>
      )}
      <button type="submit" disabled={!resized}>
        送信する
      </button>
      <p role="status">{message}</p>
    </form>
  );
}

The preview uses a URL made from the File after resizing, so that it shows the same image that will be sent. The URL is created inside the effect of useObjectUrl and released in the cleanup. The reason for this approach is described in an earlier article, "How to Receive and Display a Pasted Image in React". In testing, when I selected another image and then read the URL of the previous preview with fetch, it could no longer be read.

I pass the resized width and height to the img. Since 1280 is passed to the width attribute, unless you set the size in CSS, the display will also be 1280px wide. So on the test page, I specified max-width: 100%; height: auto in CSS to fit the image within the form's width.

In testing, when I selected a 4032×3024, 1,665 KB photo, it became a 1280×960, 52 KB JPEG, and the img in the preview also loaded at 1280×960. When sent, the server received only the resized image.

text
--- 1. Select a 4032×3024 photo ---
元の画像:4032×3024、1,665 KB
送信する画像:1280×960、52 KB
プレビューの img: {"naturalWidth":1280,"naturalHeight":960,"src":"blob:http://localhost:5173/<id>"}
--- 2. Submit ---
サーバーが受け取ったファイル: {"name":"photo.jpg","type":"image/jpeg","size":52773,"requestBytes":52957}

requestBytes is the size of the whole request the server received. It was only 184 bytes more than the image's 52,773 bytes.

If you re-select while resizing, discard the previous result

Resizing is asynchronous. If you select a large image and then select another image before the first resize finishes, two resizes run at the same time. If the image chosen later is smaller, it may finish first. If both results are passed to setResized as they are, the result of the earlier image, which finished late, overwrites the newer one.

In the ImageResizeForm effect, ignore is set to true in the cleanup. When original changes, the cleanup of the previous effect runs, so the result of the previous image is not passed to setResized. This is the same pattern as the useEffect reference example for fetching data with Effects.

In testing, I selected an 8000×6000 image and immediately re-selected an 800×600 image. After waiting 3 seconds, I checked the display. In the version without ignore set, the selected file was small.jpg, but the displayed result was from huge.jpg.

text
--- 9. Select a large image, then immediately reselect a small image ---
ImageResizeForm: {"選んでいる画像":"small.jpg","表示している結果":"元の画像:800×600、82 KB\n送信する画像:800×600、36 KB"}
ignore を立てない版: {"選んでいる画像":"small.jpg","表示している結果":"huge.jpg"}

ImageResizeForm sends the resized image. Without ignore, resized would be overwritten with the previous image's result, so sending would send the image from before the re-selection. In a form that sends the result shown in the preview as is, discarding the previous result is essential.

How much the JPEG size changes with quality

I changed quality in resizeImage and compared the sizes when the same 4032×3024 image was made into a 1280×960 JPEG.

Sizes of the 1280×960 JPEG. Quality 0.5 is 27 KB, 0.6 is 30 KB, 0.7 is 36 KB, 0.8 is 52 KB, 0.9 is 106 KB, and 1 is 643 KB. The original photo is 1,665 KB.
JPEG size for each quality setting (values for the test image)
text
--- 6. File size by JPEG quality (when a 4032×3024 photo is resized to 1280×960) ---
quality 0.5: 27631 バイト(27 KB)
quality 0.6: 30837 バイト(30 KB)
quality 0.7: 36561 バイト(36 KB)
quality 0.8: 52773 バイト(52 KB)
quality 0.9: 108453 バイト(106 KB)
quality 1: 658346 バイト(643 KB)
元の写真: 1704461 バイト

From 0.5 to 0.8, the size was 27–52 KB. At 0.9 it was about twice the size at 0.8, and at 1 it was about six times the size at 0.9. However, this image is a test image drawn with added noise, so values will differ for photos taken with a camera. Whether you can lower the quality without a visible difference needs to be checked with the images you actually handle.

Transparent PNGs: fill with white before drawing

JPEG cannot have transparent parts. The section of the HTML spec on writing canvas images to a file specifies that when writing to a format that cannot hold transparency, the image is composited over an opaque black background.

resizeImage fills the entire canvas with white before drawing the image. In testing, I converted a PNG with a transparent background to JPEG, then read the colors of the top-left corner and the center. In the version that did not fill with white, the transparent top-left corner became black.

text
--- 7. Convert a PNG with a transparent background to JPEG ---
白で塗ってから描いた版(resizeImage): {"size":"600×400","corner":"255,255,255","center":"0,200,233"}
塗らずに描いた版: {"size":"600×400","corner":"0,0,0","center":"0,200,233"}

If you want to keep the transparent parts, set the toBlob() format to image/png. In that case, remove the white fill and change the file name extension to match. I did not test writing PNG output in this article.

A JPEG with EXIF orientation is loaded at the size after orientation correction

Photos taken with a camera may have the orientation at the time of shooting written in EXIF. According to MDN's createImageBitmap() page, the default value of imageOrientation in createImageBitmap() is from-image, which follows the EXIF orientation information if it is present.

In testing, I created a JPEG of 400×300 pixels (left side light blue, right side pink) with Orientation set to 6. In the Chromium I tested, loading it with createImageBitmap() gave 300×400. The resized result was also a portrait image, with light blue at the top edge and pink at the bottom edge. The light blue that was on the left is now at the top, so the image was loaded rotated 90 degrees clockwise.

text
--- 8. JPEG with EXIF Orientation=6 (pixels are 400×300, left side light blue, right side pink) ---
createImageBitmap(file) の大きさ: "300×400"
imageOrientation: "none" を付けたとき: "300×400"
resizeImage の結果(上の端と下の端の色): {"size":"300×400","top":"0,200,233","bottom":"216,89,119"}

Because resizeImage draws the image after orientation correction onto the canvas, the written JPEG is also portrait.

Even with imageOrientation: 'none', the Chromium I tested still gave 300×400. MDN's createImageBitmap() page says that none ignores the orientation information. On the other hand, the HTML spec's imageOrientation section says that the former none was renamed to from-image, and that none will be added back later with a different meaning. So if you want to ignore orientation information, it is safer not to rely on none.

When a file that cannot be read as an image is selected

Adding accept="image/*" makes it easier to select images in the file picker. However, as MDN's accept attribute page says, this attribute only tells the browser which kinds of files to offer. It does not check the type of the file that was selected.

In testing, when I selected a file with a .jpg extension whose content was text, createImageBitmap() failed with InvalidStateError. ImageResizeForm showed a message in catch, and the submit button stayed disabled.

text
--- 5. Non-image file (not-image.jpg whose contents are text) ---
表示: "この画像は読み込めませんでした"
送信ボタン: "押せない"
createImageBitmap のエラー: "InvalidStateError: The source image could not be decoded."
Point

Resizing in the browser reduces the amount of data sent, but it does not guarantee the image the server receives. As the MDN accept attribute page also says, the server should also verify the type of the received file.

​Posted by 86