Skip to main content

EXIF orientation

A phone does not turn the pixels when you hold it sideways. It stores them as the sensor saw them and writes a number, the EXIF Orientation tag, that says how a viewer should turn the picture to show it upright. A program that ignores the tag shows the photo on its side.

libstb does not guess: by default decoding gives you the stored pixels, as every format promises. Turning is something you ask for.

import os

import libstb as stb

os.makedirs("out", exist_ok=True)

# A phone held sideways stores the picture turned and writes a tag that says how to turn it back.
info = stb.iminfo("sideways.jpg")
print("orientation tag:", info.orientation)
print("stored size:", info.width, "x", info.height)

stored = stb.Image.open("sideways.jpg") # the pixels as they are stored
upright = stb.Image.open("sideways.jpg", exif_orient=True) # turned by the tag while decoding
print("with exif_orient:", upright.width, "x", upright.height)

# Or in two steps, when you want to look at the tag first.
manual = stored.orient(info.orientation)
print("orient():", manual.width, "x", manual.height)

# All eight values of the tag, applied to the upright picture.
tiles = [upright.orient(tag) for tag in range(1, 9)]
sheet = stb.Image.hstack(tiles, gap=6, background="white", align="center")

stored.write("out/stored.png")
upright.write("out/upright.png")
sheet.write("out/orientations.png")
Output
orientation tag: 6
stored size: 100 x 150
with exif_orient: 150 x 100
orient(): 150 x 100
stored (what decoding gives)
stored (what decoding gives)
after the tag is applied
after the tag is applied

Three ways​

  1. Look at the tag. The header reports it without decoding: 1 means upright, and a picture without a tag reports 1.
  2. Decode and turn in one step with the exif_orient option. It also works for PNG files that carry an eXIf chunk, and it combines with the vertical flip option, the flip coming last.
  3. Turn afterwards with orient(tag), which takes any of the eight values and works on any image, not only one that was just decoded.

The eight values​

The tag is a number from 1 to 8: 1 is upright, 2 is a mirror, 3 a half turn, 4 a vertical mirror, 5 to 8 combine a transpose with turns and mirrors. The picture below is one upright photo with each of the eight values applied.

orient(1) to orient(8)
orient(1) to orient(8)

API at a glance​

Read the tagstb.iminfo(path).orientation
Decode and turnstb.Image.open(path, exif_orient=True)
Turn an imageimg.orient(tag)