日本語

Rotating and Flipping Images in React and Saving with Canvas

​​React​Canvas API,Playwright,TypeScript

Rotating and flipping an image only requires coordinate transforms when drawing to a canvas. For a 90° or 270° rotation, swap the canvas width and height, change the orientation with rotate() and scale(-1, 1), and then draw the image. To save, convert the canvas to a file with toBlob() and trigger a download.

Here I built Orientation, a type that represents the image's orientation, drawOriented, which draws the canvas according to it, and App, which changes the orientation with buttons and saves the result. The thing to watch out for is pressing "flip horizontally" after rotating. If you store the flip state as a plain true/false value, the picture ends up flipping top and bottom on screen instead of left and right.

Note

The test environment was Ubuntu 24.04, Node.js 22.23.4, and Chromium 153. I used React 19.3.1, TypeScript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0. With Playwright, I clicked the buttons in Chromium to save the image, then compared the saved file pixel by pixel against the same operations performed with Pillow. The test image was not a photo but a 601×401 image drawn with Pillow. I did not test Firefox, Safari, mobile browsers, formats other than PNG and JPEG, or rotation angles that are not multiples of 90°.

When "Rotate right" is pressed, the image becomes portrait. "Flip horizontally" swaps left and right, and "Flip vertically" swaps top and bottom. Pressing "Save" downloads sample-edited.png
The image’s orientation and the display below change through four operations. The changed display and file name are highlighted in pink at the moment they change. The circle in the image is the color of the original image. The cursor, operation labels, and downloaded file name are overlays added for the GIF. The button labels in the GIF are in Japanese (Rotate left, Rotate right, Flip horizontally, Flip vertically, Reset, Save)

Holding the orientation as two values: flip and rotation

There are eight possible combinations of 90° rotations and flips. So I represented the orientation with two values: whether to flip the original image horizontally, and how many degrees to rotate clockwise afterward. A vertical flip is the same as a horizontal flip followed by a 180° rotation, so it doesn't need its own value.

ts
export type Rotation = 0 | 90 | 180 | 270;

// Orientation of the image. Read as: if flip is true, first flip the original horizontally, then rotate clockwise by rotation degrees
export type Orientation = { rotation: Rotation; flip: boolean };

export const initialOrientation: Orientation = { rotation: 0, flip: false };

const normalize = (deg: number) => (((deg % 360) + 360) % 360) as Rotation;

export const rotateRight = (o: Orientation): Orientation => ({ ...o, rotation: normalize(o.rotation + 90) });
export const rotateLeft = (o: Orientation): Orientation => ({ ...o, rotation: normalize(o.rotation - 90) });

// Swap left and right while keeping the orientation currently shown on screen
export const flipHorizontal = (o: Orientation): Orientation => ({ rotation: normalize(-o.rotation), flip: !o.flip });
// Swap top and bottom while keeping the orientation currently shown on screen
export const flipVertical = (o: Orientation): Orientation => ({ rotation: normalize(180 - o.rotation), flip: !o.flip });

The key point is that flipHorizontal does not just toggle flip; it also sets the angle to -rotation. Since Orientation is defined so that the flip is applied before the rotation, swapping the image left and right on screen after it has been rotated requires adding the flip and reversing the direction of rotation. The vertical flip is that operation followed by another 180° rotation.

All four functions take the previous orientation and return a new one. That means you can pass them directly as state updater functions, such as setOrientation(rotateRight).

When drawing to a canvas, move the origin first, then rotate

rotate() rotates clockwise around the canvas origin (the top-left corner). You can't change the center of rotation, so to make the rotated image fit exactly starting at the top-left (0, 0), first move the origin with translate(). For horizontal flipping, use scale() with -1, which swaps left and right.

ts
// Draw the reoriented image on the canvas. For 90° and 270°, swap the canvas width and height
export function drawOriented(canvas: HTMLCanvasElement, image: ImageBitmap, { rotation, flip }: Orientation) {
  const w = image.width;
  const h = image.height;
  const sideways = rotation === 90 || rotation === 270;
  canvas.width = sideways ? h : w;
  canvas.height = sideways ? w : h;

  const ctx = canvas.getContext('2d');
  if (!ctx) throw new Error('canvas が使えません');
  // Move the origin first so that the rotated image fits exactly from the top-left (0, 0) of the canvas
  if (rotation === 90) ctx.translate(h, 0);
  if (rotation === 180) ctx.translate(w, h);
  if (rotation === 270) ctx.translate(0, w);
  ctx.rotate((rotation * Math.PI) / 180);
  if (flip) {
    ctx.translate(w, 0);
    ctx.scale(-1, 1);
  }
  ctx.drawImage(image, 0, 0);
}

Resetting the canvas width and height clears the existing drawing and transforms. So calling this function on every button press does not accumulate previous rotations.

Save with toBlob and a download link

To save, convert the canvas to a Blob with toBlob(), then click a link with the download attribute to start the download.

ts
export function canvasToBlob(canvas: HTMLCanvasElement, type: string, quality?: number): Promise<Blob> {
  return new Promise((resolve, reject) => {
    canvas.toBlob((blob) => (blob ? resolve(blob) : reject(new Error('画像を書き出せませんでした'))), type, quality);
  });
}

// Trigger a download of the Blob as a file
export function downloadBlob(blob: Blob, filename: string) {
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  a.click();
  URL.revokeObjectURL(url);
}

I call URL.revokeObjectURL() right after click(). In the Chromium I tested, every save still produced a downloaded file.

A component that changes the orientation with buttons and saves

In App, the selected file is loaded with createImageBitmap(), and the preview canvas is redrawn with drawOriented every time the orientation changes. When saving, the preview canvas itself is converted to a file. The display is shrunk with CSS, but the canvas itself has the same resolution as the original image, so the image saved has the orientation shown on screen at its original size.

tsx
import { useEffect, useRef, useState } from 'react';
import type { ChangeEvent } from 'react';
import {
  drawOriented, flipHorizontal, flipVertical, initialOrientation, rotateLeft, rotateRight,
} from './orientation';
import type { Orientation } from './orientation';
import { canvasToBlob, downloadBlob } from './save';

type Loaded = { bitmap: ImageBitmap; name: string; type: string };

export function App() {
  const [image, setImage] = useState<Loaded | null>(null);
  const [orientation, setOrientation] = useState<Orientation>(initialOrientation);
  const canvasRef = useRef<HTMLCanvasElement>(null);

  // Redraw the preview canvas every time the orientation changes
  useEffect(() => {
    if (image && canvasRef.current) drawOriented(canvasRef.current, image.bitmap, orientation);
  }, [image, orientation]);

  async function handleFile(e: ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    const bitmap = await createImageBitmap(file);
    image?.bitmap.close();
    setOrientation(initialOrientation);
    setImage({ bitmap, name: file.name, type: file.type });
  }

  async function handleSave() {
    const canvas = canvasRef.current;
    if (!image || !canvas) return;
    // Save JPEG as JPEG, and everything else as PNG
    const type = image.type === 'image/jpeg' ? 'image/jpeg' : 'image/png';
    const blob = await canvasToBlob(canvas, type, 0.92);
    const base = image.name.replace(/\.[^.]+$/, '');
    downloadBlob(blob, `${base}-edited.${type === 'image/jpeg' ? 'jpg' : 'png'}`);
  }

  const sideways = orientation.rotation % 180 !== 0;

  return (
    <main>
      <input type="file" accept="image/*" aria-label="画像を選ぶ" onChange={handleFile} />
      {image && (
        <>
          <div className="toolbar">
            <button type="button" onClick={() => setOrientation(rotateLeft)}>左に回す</button>
            <button type="button" onClick={() => setOrientation(rotateRight)}>右に回す</button>
            <button type="button" onClick={() => setOrientation(flipHorizontal)}>左右反転</button>
            <button type="button" onClick={() => setOrientation(flipVertical)}>上下反転</button>
            <button type="button" onClick={() => setOrientation(initialOrientation)}>元に戻す</button>
          </div>
          <canvas ref={canvasRef} className="preview" role="img" aria-label="向きを変えた画像のプレビュー" />
          <p className="info">
            回転:{orientation.rotation}° / 反転:{orientation.flip ? 'あり' : 'なし'} / 保存する大きさ:
            {sideways ? image.bitmap.height : image.bitmap.width}×{sideways ? image.bitmap.width : image.bitmap.height}px
          </p>
          <button type="button" className="save" onClick={handleSave}>保存する</button>
        </>
      )}
    </main>
  );
}

To fit the preview within the screen width, I applied the following CSS.

css
.preview { display: block; max-width: 100%; max-height: 360px; height: auto; width: auto; border: 1px solid #ccd; }

Comparing saved images with the same operations in Pillow

I selected a 601×401 PNG and saved it after pressing the buttons in different orders. Below are some of the results of comparing each saved file pixel by pixel with an image rotated and flipped in the same order using Pillow, the Python image library.

text
右に回す: PNG 401x601 RGBA | 色が違う画素 0 / 241001
左に回す: PNG 401x601 RGBA | 色が違う画素 0 / 241001
上下反転: PNG 601x401 RGBA | 色が違う画素 0 / 241001
右に回す → 左右反転: PNG 401x601 RGBA | 色が違う画素 0 / 241001
右に回す → 上下反転: PNG 401x601 RGBA | 色が違う画素 0 / 241001
左右反転 → 右に回す: PNG 401x601 RGBA | 色が違う画素 0 / 241001
右に回す → 左右反転 → 左に回す → 上下反転: PNG 601x401 RGBA | 色が違う画素 0 / 241001

Across all 15 button sequences I tried, the number of pixels with a different color was 0. Even for an image with odd width and height, rotation did not blur any pixels. For sequences where rotation and flipping cancel each other out, such as "Rotate right → Flip horizontally → Rotate left → Flip vertically," the display also returns to "Rotation: 0° / Flip: none." Even though the original image was RGB, the saved PNG was RGBA with transparency included.

Storing flips as true/false makes a horizontal flip after rotating appear as a vertical flip

For comparison, I also drew the image using a version that stores horizontal and vertical flips separately as flipX and flipY booleans. If you just toggle the values on each button press, the state after rotating right and then pressing "Flip horizontally" becomes rotation: 90, flipX: true. When drawing, the origin is moved to the center of the canvas, the image is rotated, and then scale(flipX ? -1 : 1, flipY ? -1 : 1) is applied.

ts
ctx.translate(canvas.width / 2, canvas.height / 2);
ctx.rotate((rotation * Math.PI) / 180);
ctx.scale(flipX ? -1 : 1, flipY ? -1 : 1);
ctx.drawImage(image, -w / 2, -h / 2);

I compared the image drawn this way with the expected result.

text
右に回す → 左右反転: 期待(右に回す → 左右反転)と比べて 色が違う画素 126478 / 241001 | 右に回す → 上下反転 と比べて 色が違う画素 0 / 241001

More than half of the pixels differed from the expected image, but it matched the image rotated right and then flipped vertically exactly. In other words, with this approach flipX swaps the left and right of the original image, not the left and right on screen. After a 90° rotation, this appears on screen as a swap of top and bottom. If you convert the operation as seen on screen into the orientation values, as flipHorizontal does in the first section, this mismatch doesn't occur.

With CSS transform rotation, the surrounding layout stays as it was before rotating

For the preview alone, you can rotate an <img> with transform: rotate(90deg). However, a CSS transform does not affect the layout of surrounding elements. I rotated a 300px wide <img> by 90° and measured the surrounding dimensions.

text
枠(.box): top 0, 幅 304, 高さ 204.15625
img の見た目: top -47.921875, 幅 200.15625, 高さ 300
次の段落: top 220.15625, 幅 560, 高さ 21

The visible image became 300px tall, but the height of the enclosing box stayed at about 204px, which is the original image height (about 200px) plus the border. The image overflows the top of the box by about 48px, and its bottom overlaps the next paragraph. With the canvas redraw method, the canvas's own width and height are swapped, so this kind of mismatch does not occur. Another benefit is that the saved image and the preview are produced by the same processing.

Quality and EXIF orientation when saving as JPEG

If the original image is a JPEG, the image is saved as JPEG using 'image/jpeg' and quality 0.92 in toBlob(). Because JPEG is compressed again on save, the pixel values will not match the original exactly. Below is the result of comparing a JPEG rotated right and saved with the same operation done in Pillow.

text
保存した画像: JPEG 401x601 EXIF の Orientation = None
元の JPEG を Pillow で右に回した画像と比べて: 色が違う画素 77735 / 241001、差のいちばん大きい画素で 57(0〜255)

JPEG has a mechanism to store the image without rotating the pixels, and to record the display orientation in the EXIF Orientation tag (ExifTool's list of Orientation values). createImageBitmap() applies this EXIF orientation when loading, unless imageOrientation is specified. To check how the button rotation combines with the EXIF orientation, I used the following JPEG. It was a test image rotated 90° left and saved at 401×601, with Orientation=6 added (meaning rotate 90° clockwise when displayed).

text
何も押さない: 回転:0° / 反転:なし / 保存する大きさ:601×401px | 保存したファイル名: exif6-edited.jpg
右に回す: 回転:90° / 反転:なし / 保存する大きさ:401×601px | 保存したファイル名: exif6-edited.jpg

When loaded, the image was treated as 601×401 with the EXIF orientation applied. The saved image had no Orientation tag, and the pixels themselves were in the correct orientation. Compared with the Pillow-processed version of the original image, the average difference, excluding noisy areas, was 1.40 for the image saved without pressing any button and 1.41 for the image saved after rotating right. Compared with an image rotated 180°, both were 51.94. The button rotation is applied on top of the corrected view after the EXIF orientation is applied, so the image is saved in the orientation seen on screen.

​Posted by 86