Skip to content
← Public packages

@kentcdodds/photo-portfolio

A fast, photo-first portfolio site you update by chatting with your agent: galleries, about, contact, and one-step rollback.

FollowFork

Files

exif.ts

244 lines · 7.2 KB · TypeScript
import type { PhotoCredits } from '../domain/types.ts'

export type ExifInfo = {
	/** EXIF orientation 1–8 (1 = upright). */
	orientation: number
	credits: PhotoCredits
}

const tags = {
	orientation: 0x0112,
	make: 0x010f,
	model: 0x0110,
	artist: 0x013b,
	copyright: 0x8298,
	exifIfd: 0x8769,
	exposureTime: 0x829a,
	fNumber: 0x829d,
	iso: 0x8827,
	dateTimeOriginal: 0x9003,
	focalLength: 0x920a,
	lensModel: 0xa434,
} as const

/** Find the APP1 "Exif\0\0" payload (the TIFF block) in a JPEG. */
function findJpegExif(bytes: Uint8Array): Uint8Array | null {
	if (bytes[0] !== 0xff || bytes[1] !== 0xd8) return null
	let offset = 2
	while (offset + 4 <= bytes.length) {
		if (bytes[offset] !== 0xff) return null
		const marker = bytes[offset + 1]!
		if (marker === 0xda || marker === 0xd9) return null
		const length = (bytes[offset + 2]! << 8) | bytes[offset + 3]!
		const start = offset + 4
		if (
			marker === 0xe1 &&
			length >= 8 &&
			bytes[start] === 0x45 &&
			bytes[start + 1] === 0x78 &&
			bytes[start + 2] === 0x69 &&
			bytes[start + 3] === 0x66 &&
			bytes[start + 4] === 0 &&
			bytes[start + 5] === 0
		) {
			return bytes.subarray(start + 6, offset + 2 + length)
		}
		offset += 2 + length
	}
	return null
}

type Entry = { type: number; count: number; valueOffset: number }

function readIfd(view: DataView, offset: number, little: boolean) {
	const entries = new Map<number, Entry>()
	if (offset + 2 > view.byteLength) return entries
	const count = view.getUint16(offset, little)
	for (let i = 0; i < count; i += 1) {
		const at = offset + 2 + i * 12
		if (at + 12 > view.byteLength) break
		entries.set(view.getUint16(at, little), {
			type: view.getUint16(at + 2, little),
			count: view.getUint32(at + 4, little),
			valueOffset: at + 8,
		})
	}
	return entries
}

const typeSizes: Record<number, number> = {
	1: 1,
	2: 1,
	3: 2,
	4: 4,
	5: 8,
	7: 1,
	9: 4,
	10: 8,
}

function dataOffset(view: DataView, entry: Entry, little: boolean) {
	const size = (typeSizes[entry.type] ?? 1) * entry.count
	return size <= 4
		? entry.valueOffset
		: view.getUint32(entry.valueOffset, little)
}

const utf8 = new TextDecoder()

function readAscii(view: DataView, entry: Entry | undefined, little: boolean) {
	if (!entry || entry.type !== 2) return undefined
	const start = dataOffset(view, entry, little)
	const end = Math.min(start + entry.count, view.byteLength)
	const raw = new Uint8Array(
		view.buffer,
		view.byteOffset + start,
		Math.max(0, end - start),
	)
	const terminator = raw.indexOf(0)
	// EXIF says ASCII, but cameras and editors commonly write UTF-8 (e.g. "©").
	const text = utf8
		.decode(terminator >= 0 ? raw.subarray(0, terminator) : raw)
		.trim()
	return text || undefined
}

function readNumber(view: DataView, entry: Entry | undefined, little: boolean) {
	if (!entry) return undefined
	const start = dataOffset(view, entry, little)
	if (start + 8 > view.byteLength && (entry.type === 5 || entry.type === 10))
		return undefined
	switch (entry.type) {
		case 3:
			return view.getUint16(start, little)
		case 4:
			return view.getUint32(start, little)
		case 5: {
			const denominator = view.getUint32(start + 4, little)
			return denominator
				? view.getUint32(start, little) / denominator
				: undefined
		}
		case 10: {
			const denominator = view.getInt32(start + 4, little)
			return denominator
				? view.getInt32(start, little) / denominator
				: undefined
		}
		default:
			return undefined
	}
}

function formatShutter(seconds: number) {
	if (seconds >= 1) return `${Number(seconds.toFixed(1))}s`
	return `1/${Math.round(1 / seconds)}s`
}

/**
 * Read orientation and basic credit fields from a JPEG's EXIF block.
 * GPS, serial numbers, and everything else are ignored (and never written back).
 */
export function readExif(bytes: Uint8Array): ExifInfo {
	const empty: ExifInfo = { orientation: 1, credits: {} }
	const tiff = findJpegExif(bytes)
	if (!tiff || tiff.length < 8) return empty
	try {
		const view = new DataView(tiff.buffer, tiff.byteOffset, tiff.byteLength)
		const little = view.getUint16(0) === 0x4949
		if (view.getUint16(2, little) !== 42) return empty
		const ifd0 = readIfd(view, view.getUint32(4, little), little)
		const exifPointer = readNumber(view, ifd0.get(tags.exifIfd), little)
		const exif = exifPointer
			? readIfd(view, exifPointer, little)
			: new Map<number, Entry>()

		const orientation =
			readNumber(view, ifd0.get(tags.orientation), little) ?? 1
		const make = readAscii(view, ifd0.get(tags.make), little)
		const model = readAscii(view, ifd0.get(tags.model), little)
		const camera = model
			? make && !model.startsWith(make)
				? `${make} ${model}`
				: model
			: make
		const fNumber = readNumber(view, exif.get(tags.fNumber), little)
		const shutter = readNumber(view, exif.get(tags.exposureTime), little)
		const iso = readNumber(view, exif.get(tags.iso), little)
		const focal = readNumber(view, exif.get(tags.focalLength), little)
		const exposure = [
			focal ? `${Math.round(focal)}mm` : null,
			fNumber ? `ƒ/${Number(fNumber.toFixed(1))}` : null,
			shutter ? formatShutter(shutter) : null,
			iso ? `ISO ${iso}` : null,
		]
			.filter(Boolean)
			.join(' · ')
		const taken = readAscii(view, exif.get(tags.dateTimeOriginal), little)
		const takenAt = taken?.replace(/^(\d{4}):(\d{2}):(\d{2})/, '$1-$2-$3')

		const credits: PhotoCredits = {}
		const artist = readAscii(view, ifd0.get(tags.artist), little)
		const copyright = readAscii(view, ifd0.get(tags.copyright), little)
		const lens = readAscii(view, exif.get(tags.lensModel), little)
		if (artist) credits.artist = artist
		if (copyright) credits.copyright = copyright
		if (camera) credits.camera = camera
		if (lens) credits.lens = lens
		if (exposure) credits.exposure = exposure
		if (takenAt) credits.takenAt = takenAt
		return {
			orientation: orientation >= 1 && orientation <= 8 ? orientation : 1,
			credits,
		}
	} catch {
		return empty
	}
}

/**
 * Build a minimal EXIF APP1 payload ("Exif\0\0" + little-endian TIFF) with only
 * Artist and Copyright. This is the only metadata written into output JPEGs.
 */
export function buildCreditExif(input: {
	artist: string
	copyright: string
}): Uint8Array {
	const encoder = new TextEncoder()
	const fields = [
		{ tag: tags.artist, value: encoder.encode(`${input.artist}\0`) },
		{ tag: tags.copyright, value: encoder.encode(`${input.copyright}\0`) },
	]
	const ifdSize = 2 + fields.length * 12 + 4
	let dataCursor = 8 + ifdSize
	const total =
		dataCursor +
		fields.reduce(
			(sum, f) => sum + (f.value.length > 4 ? f.value.length : 0),
			0,
		)
	const tiff = new Uint8Array(total)
	const view = new DataView(tiff.buffer)
	tiff.set([0x49, 0x49], 0)
	view.setUint16(2, 42, true)
	view.setUint32(4, 8, true)
	view.setUint16(8, fields.length, true)
	fields.forEach((field, index) => {
		const at = 10 + index * 12
		view.setUint16(at, field.tag, true)
		view.setUint16(at + 2, 2, true)
		view.setUint32(at + 4, field.value.length, true)
		if (field.value.length <= 4) {
			tiff.set(field.value, at + 8)
		} else {
			view.setUint32(at + 8, dataCursor, true)
			tiff.set(field.value, dataCursor)
			dataCursor += field.value.length
		}
	})
	view.setUint32(10 + fields.length * 12, 0, true)
	const payload = new Uint8Array(6 + tiff.length)
	payload.set([0x45, 0x78, 0x69, 0x66, 0, 0], 0)
	payload.set(tiff, 6)
	return payload
}