AI Image API EXIF Orientation: Normalize Rotated Photos
Your application accepts a portrait reference photo, generates an image, and creates a thumbnail. The reference looks upright on a phone but sideways in the worker. AI image API EXIF orientation handling addresses this mismatch by transforming decoded pixels into their intended display orientation before downstream processing. Do not assume that reference uploads, generated results, and browser previews interpret metadata identically.
This tutorial implements an application-owned normalization stage with Python and Pillow. It does not introduce a GenRelay request parameter or claim that every generated image contains orientation metadata. Apply the stage wherever your pipeline accepts image files whose pixel orientation you have not already normalized, including user references and downloaded outputs.
What does EXIF orientation actually describe?
EXIF orientation describes how stored pixels should be rotated or mirrored for display; it does not change the stored pixel array itself.
EXIF, short for Exchangeable Image File Format, is metadata that can accompany an image. Its Orientation tag, numeric identifier 274, has eight defined values. Value 1 represents normal display orientation. Other values describe rotations, reflections, or combinations of both. Supporting rotation alone misses mirrored selfies and transposed images.
A decoder that ignores the tag can report a landscape pixel array for a picture viewers display as portrait. For example, an illustrative 1200-by-800 stored image with orientation 6 displays as 800-by-1200 after normalization. These are example dimensions, not GenRelay output specifications.
Pillow's ImageOps.exif_transpose applies the tag's transform and removes the orientation instruction from the returned image. Removing that instruction matters: keeping the old transform after rotating pixels can make a later viewer apply it again.
An image without the tag is not necessarily upright. It simply has no metadata instruction available to resolve the question. Do not guess orientation from aspect ratio or subject recognition without a separate product requirement.
Where should orientation correction happen in an image pipeline?
Normalize after validating the input and before resizing, cropping, or computing pixel-based geometry.
Use this processing order:
- Acquire the file into private, size-bounded staging storage.
- Check the decoded format, dimensions, frame count, and orientation value.
- Decode under resource limits and apply the orientation transform.
- Perform any separately defined color conversion or privacy cleanup.
- Create delivery derivatives from normalized pixels.
- Validate the saved artifact, then publish its storage reference.
If a user draws a crop rectangle over an upright browser preview, those coordinates refer to displayed geometry. Applying the rectangle to untransformed stored pixels crops the wrong region. Keep crop coordinates in a documented coordinate space, and derive them from the same normalized image used by your worker.
For integration context, start with the GenRelay image API overview. The processing function below begins with an application-owned local file; acquisition, authentication, and generation remain separate responsibilities.
Avoid normalizing only the thumbnail while leaving the source used for later editing unnormalized. Instead, record a normalized master identifier and transformation version, then consistently derive previews and edited assets from that master.
How do I normalize a local reference image with Python?
Use ImageOps.exif_transpose inside a bounded decoder, save into a new image object, and atomically replace the destination only after checking the encoded result.
Install Pillow in your application's managed Python environment. The following example accepts single-frame JPEG and PNG inputs and writes a PNG master. Its limits are illustrative application policies, not platform quotas. It deliberately does not download URLs or send generation requests.
from pathlib import Path
import os
import tempfile
import warnings
from PIL import Image, ImageOps
MAX_BYTES = 20 * 1024 * 1024
MAX_PIXELS = 16_000_000
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
def normalize_image(source, destination):
source, destination = Path(source), Path(destination)
if source.resolve() == destination.resolve():
raise ValueError("Keep the source and destination separate")
if not 0 < source.stat().st_size <= MAX_BYTES:
raise ValueError("Input byte limit")
destination.parent.mkdir(parents=True, exist_ok=True)
with warnings.catch_warnings():
warnings.simplefilter("error", Image.DecompressionBombWarning)
with Image.open(source) as image:
if image.format not in {"JPEG", "PNG"}:
raise ValueError("Unsupported decoded format")
if getattr(image, "n_frames", 1) != 1:
raise ValueError("Single-frame input required")
width, height = image.size
if min(width, height) <= 0 or width * height > MAX_PIXELS:
raise ValueError("Input pixel limit")
orientation = image.getexif().get(274, 1)
if type(orientation) is not int or orientation not in range(1, 9):
raise ValueError("Invalid orientation")
if image.mode not in {"RGB", "RGBA"}:
raise ValueError("Separate color conversion required")
if image.info.get("icc_profile"):
raise ValueError("Normalize the color profile separately")
image.load()
oriented = ImageOps.exif_transpose(image)
clean = Image.new(oriented.mode, oriented.size)
clean.paste(oriented)
fd, temporary = tempfile.mkstemp(
prefix="normalize-", suffix=".png", dir=destination.parent
)
os.close(fd)
try:
clean.save(temporary, format="PNG")
with Image.open(temporary) as check:
check.load()
if check.size != clean.size or check.mode != clean.mode:
raise ValueError("Output geometry or mode mismatch")
if check.getexif().get(274) is not None:
raise ValueError("Orientation instruction remains")
os.replace(temporary, destination)
finally:
if os.path.exists(temporary):
os.unlink(temporary)
return clean.size
The new image object avoids implicitly copying source metadata into the normalized PNG. This is an output policy, not a substitute for auditing every encoding path. The example preserves RGBA pixels, including transparency; it does not flatten them onto a background.
It also rejects embedded ICC profiles rather than stripping them and silently changing color interpretation. An ICC profile describes how color values map to a color space. Production applications accepting profiled or CMYK images should implement a color-managed branch, then normalize orientation before geometry-dependent work.
Use a private staging directory that other tenants cannot modify. The byte check assumes the local input remains unchanged between inspection and decoding. For hostile uploads, enforce acquisition limits, immutable staging, process memory ceilings, and wall-clock deadlines outside this function as well.
How can I test all eight orientation values?
Create an asymmetric fixture and compare every output against an explicit expected transform, not just an expected width and height.
A square or visually symmetric test image can hide incorrect reflections. The following regression test uses different corner colors, exercises values 1 through 8, checks metadata removal, and repeats normalization to detect double transformation. Save the previous snippet as normalize_orientation.py and this snippet beside it.
from pathlib import Path
from tempfile import TemporaryDirectory
from PIL import Image
from normalize_orientation import normalize_image
T = Image.Transpose
expected_ops = {
1: None,
2: T.FLIP_LEFT_RIGHT,
3: T.ROTATE_180,
4: T.FLIP_TOP_BOTTOM,
5: T.TRANSPOSE,
6: T.ROTATE_270,
7: T.TRANSVERSE,
8: T.ROTATE_90,
}
with TemporaryDirectory() as directory:
root = Path(directory)
base = Image.new("RGB", (7, 5), "white")
for point, color in [
((0, 0), "red"), ((6, 0), "green"),
((0, 4), "blue"), ((6, 4), "yellow"),
]:
base.putpixel(point, Image.new("RGB", (1, 1), color).getpixel((0, 0)))
for orientation, operation in expected_ops.items():
source = root / f"input-{orientation}.png"
output = root / f"output-{orientation}.png"
second = root / f"second-{orientation}.png"
exif = Image.Exif()
exif[274] = orientation
base.save(source, exif=exif)
normalize_image(source, output)
expected = base if operation is None else base.transpose(operation)
with Image.open(output) as actual:
assert actual.size == expected.size
assert actual.tobytes() == expected.tobytes()
assert actual.getexif().get(274) is None
normalize_image(output, second)
with Image.open(second) as repeated:
assert repeated.tobytes() == expected.tobytes()
print("Eight orientations and repeat-normalization checks passed")
PNG keeps these test pixels lossless, making byte-for-byte decoded comparisons meaningful. JPEG fixtures require comparison against the decoded JPEG source, because lossy encoding changes pixels before orientation processing even begins.
Add separate fixtures for missing tags, invalid values, corrupt files, transparency, oversized dimensions, and files with disallowed color profiles. Run the suite when upgrading Pillow or changing your encoder settings.
How does normalization affect resizing, caching, and costs?
Normalization changes processing and storage decisions, but it does not require another paid image generation.
For image resizing and cropping, compute target dimensions after the transform. Orientations that swap axes also swap the source width and height used in aspect-ratio calculations. Keep the source unchanged for support investigations, subject to your retention policy.
A cache key identifies which stored result a request may reuse. Include the source content identifier, normalization version, crop policy, and derivative settings in application cache keys. Do not assume an old thumbnail remains valid after changing orientation logic. Keep tenant authorization checks separate from content equality.
As of November 16, 2026, the supplied GenRelay generation prices are $0.014 per GPT-image-2 image; Nano Banana 2 is $0.020 at 1K and $0.036 at 4K; Nano Banana Pro is $0.030 at 1K or 2K and $0.042 at 4K. Generating 1,000 GPT-image-2 images therefore costs $14 in generation charges at that quoted unit price, before application processing and storage.
Reprocessing those existing images locally is not another generation request. Track decoder CPU time, master-file storage, derivative storage, and delivery traffic separately. Never describe PNG normalization as free overall merely because it avoids a new generation call.
What should developers know before shipping orientation handling?
Ship orientation correction with explicit metadata, failure, and observability policies rather than treating it as a cosmetic fix.
Record the observed orientation value, original dimensions, normalized dimensions, processing version, and outcome. Avoid logging complete EXIF blobs, file download credentials, or private source URLs. For a broader cleanup policy, see EXIF privacy for image API pipelines.
Reject invalid input into a reviewable failure state without automatically regenerating the image. A processing failure and a generation failure have different recovery costs. Retry local processing only when the source is intact and the reason is understood.
Does every generated image need an orientation transform?
No. Missing orientation metadata normally means there is no metadata-driven transform to apply. Use a consistent normalization stage, but do not invent rotations based on whether an image looks portrait or landscape.
Does removing EXIF automatically rotate the pixels?
No. Removing the tag first can discard the instruction needed to display the image correctly. Apply the transform before stripping metadata, then confirm the output has no stale orientation instruction.
Can orientation correction preserve transparency?
Yes. The example preserves RGBA mode and reorders pixels without flattening alpha. A later JPEG export needs a separate, explicit background-compositing policy.
Is orientation normalization the same as color management?
No. Orientation determines geometry; color management determines how pixel values should be interpreted. Handle both deliberately, and test their combined output before publishing derivatives to users.