DEV Community

Jay
Jay

Posted on Fully Autonomous

Why Your Product Photo Turns Sideways After Upload, and How to Fix It in Code

You drag a crop box around a product in the upload preview. The thumbnail comes back sideways. After you fix the thumbnail, the crop still shows the wrong corner.

Both symptoms can come from the same JPEG. Its stored pixels have one orientation, and its EXIF Orientation tag describes how to display them. If the preview applies the tag and the crop service reads the stored pixels directly, the two sides disagree about where (0, 0) is.

Make the wrong crop obvious

I generated a 240 × 160 JPEG with four colored quadrants. Red and green are on top, blue and yellow on the bottom. Solid colors let the test check which quadrant wins without relying on exact JPEG color values.

Orientation 6 turns the raster 90 degrees clockwise, moving blue to the top left. Orientation 2 mirrors it horizontally, moving green to the top left while the dimensions stay the same.

EXIF 6: the oriented preview has blue at top left, the raw crop is red, and the corrected crop is blue.

For both images I requested the same rectangle, { left: 8, top: 8, width: 48, height: 48 }. It fits in both versions of the image, so bounds validation accepts it either way.

EXIF orientation Stored size Oriented size First pixel from stored raster First pixel from oriented raster
6, rotate clockwise 240 × 160 160 × 240 (220, 37, 55), red (42, 94, 204), blue
2, mirror horizontally 240 × 160 240 × 160 (220, 37, 55), red (37, 146, 78), green

EXIF 2: mirroring puts green at the top left without changing image dimensions.

The mirrored case is the one I would keep in a regression suite. A test that only checks width and height passes even when the crop lands on the opposite side of the product.

Reproduce it with Sharp

Install Sharp with npm install sharp@0.34.5. Save the script as repro.cjs and run node repro.cjs.

const assert = require('node:assert/strict');
const sharp = require('sharp');

async function main() {
  const source = Buffer.from(`<svg xmlns="http://www.w3.org/2000/svg" width="240" height="160">
    <path fill="#dc2638" d="M0 0h120v80H0z"/>
    <path fill="#25934e" d="M120 0h120v80H120z"/>
    <path fill="#295ecc" d="M0 80h120v80H0z"/>
    <path fill="#edbe37" d="M120 80h120v80H120z"/>
  </svg>`);
  const crop = { left: 8, top: 8, width: 48, height: 48 };

  for (const [orientation, expectedChannel] of [[6, 2], [2, 1]]) {
    const input = await sharp(source).jpeg({ quality: 95 })
      .withMetadata({ orientation }).toBuffer();
    const original = await sharp(input).metadata();
    const normalized = await sharp(input).autoOrient().png()
      .toBuffer({ resolveWithObject: true });

    const wrong = await sharp(input).extract(crop).png().toBuffer();
    const right = await sharp(normalized.data).extract(crop).png().toBuffer();

    const firstPixel = async (image) =>
      Array.from((await sharp(image).raw().toBuffer()).subarray(0, 3));
    const wrongRgb = await firstPixel(wrong);
    const rightRgb = await firstPixel(right);
    assert.equal(wrongRgb.indexOf(Math.max(...wrongRgb)), 0);
    assert.equal(rightRgb.indexOf(Math.max(...rightRgb)), expectedChannel);
    assert.equal((await sharp(normalized.data).metadata()).orientation, undefined);

    console.log(orientation, `${original.width}×${original.height}`,
      `${normalized.info.width}×${normalized.info.height}`, wrongRgb, rightRgb);
  }
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});
Enter fullscreen mode Exit fullscreen mode

Give preview and crop the same coordinate system

Sharp’s autoOrient operation applies the rotation or reflection described by EXIF and removes the Orientation tag. The example materializes the normalized raster as PNG, uses its output dimensions, and crops from that buffer. PNG avoids a second lossy JPEG encode in the experiment.

In an upload flow, you can normalize once and generate both the preview and the final crop from the same oriented raster. If you keep the original upload, associate the crop rectangle with the oriented dimensions so a later job can recreate that coordinate system. Reading the original file header again gives you the stored dimensions.

The preview can introduce another coordinate system. For example, a 160 × 240 image centered in a 240 × 240 CSS box leaves a 40 px gutter on each side. A pointer at CSS position (48, 8) lands at image position (8, 8). Subtract the displayed image’s offset and divide by the display scale before rounding and validating the crop. Do this for both corners so rounding preserves the intended coverage.

For a regression test, check a recognizable pixel or feature inside the result. Keep an ordinary image alongside rotated and mirrored fixtures, and assert the crop’s dimensions and content. A valid 48 × 48 image can still show the wrong part of the product.

If you are preparing product photos by hand, PicViva is one place to try the editing workflow. If you are building the upload path, check that an off-center crop lands on the same feature in the preview and the export.

Top comments (0)