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

process.ts

132 lines · 3.6 KB · TypeScript
import jpeg from 'jpeg-js'
import { encode as encodeWebp } from '@stacksjs/ts-webp'
import { encode as encodeBlurhash } from 'blurhash'
import { planVariantSizes, variantFormats } from '../domain/image-plan.ts'
import type { PhotoCredits, PhotoVariant } from '../domain/types.ts'
import { bytesToBase64 } from '../store/base64.ts'
import { buildCreditExif, readExif } from './exif.ts'
import {
	applyOrientation,
	decodeImage,
	orientedSize,
	resize,
	sniffFormat,
	type Pixels,
} from './pixels.ts'

export const jpegQuality = 80
export const webpQuality = 72

export type ProcessedFile = { variant: PhotoVariant; bytes: Uint8Array }

export type ProcessedImage = {
	width: number
	height: number
	blurhash: string
	lqip: string
	credits: PhotoCredits
	files: Array<ProcessedFile>
}

export type ProcessOptions = {
	/** When set, written into each JPEG's EXIF Artist/Copyright. Nothing else is kept. */
	creditExif?: { artist: string; copyright: string }
}

function scaledToFit(pixels: Pixels, width: number) {
	const height = Math.max(1, Math.round((pixels.height * width) / pixels.width))
	return resize(pixels, width, height)
}

/**
 * Turn one uploaded photo into web-ready files: every planned width as WebP and
 * JPEG, upright (EXIF orientation applied), metadata stripped except optional
 * credits, plus a BlurHash and a tiny JPEG placeholder.
 */
export async function processImage(
	bytes: Uint8Array,
	options: ProcessOptions = {},
): Promise<ProcessedImage> {
	const format = sniffFormat(bytes)
	const exif =
		format === 'jpeg' ? readExif(bytes) : { orientation: 1, credits: {} }
	const source = await decodeImage(bytes)
	const upright = orientedSize(source.width, source.height, exif.orientation)
	const sizes = planVariantSizes(upright.width, upright.height)
	const exifPayload = options.creditExif
		? buildCreditExif(options.creditExif)
		: undefined

	const files: Array<ProcessedFile> = []
	for (const size of sizes) {
		const raw = orientedSize(size.width, size.height, exif.orientation)
		const pixels = applyOrientation(
			resize(source, raw.width, raw.height),
			exif.orientation,
		)
		for (const variantFormat of variantFormats) {
			const encoded =
				variantFormat === 'webp'
					? encodeWebp(
							{ data: pixels.data, width: pixels.width, height: pixels.height },
							{ lossless: false, quality: webpQuality },
						)
					: new Uint8Array(
							jpeg.encode(
								{
									data: pixels.data,
									width: pixels.width,
									height: pixels.height,
									...(exifPayload ? { exifBuffer: exifPayload } : {}),
								} as Parameters<typeof jpeg.encode>[0],
								jpegQuality,
							).data,
						)
			files.push({
				variant: {
					width: pixels.width,
					height: pixels.height,
					format: variantFormat,
					bytes: encoded.length,
				},
				bytes: encoded,
			})
		}
	}

	const thumbHeight = Math.max(
		1,
		Math.round((32 * upright.height) / upright.width),
	)
	const thumbRaw = orientedSize(32, thumbHeight, exif.orientation)
	const thumbSource = applyOrientation(
		resize(source, thumbRaw.width, thumbRaw.height),
		exif.orientation,
	)
	const blurhash = encodeBlurhash(
		new Uint8ClampedArray(
			thumbSource.data.buffer,
			thumbSource.data.byteOffset,
			thumbSource.data.byteLength,
		),
		thumbSource.width,
		thumbSource.height,
		4,
		3,
	)
	const tiny = scaledToFit(thumbSource, 16)
	const lqipBytes = new Uint8Array(
		jpeg.encode({ data: tiny.data, width: tiny.width, height: tiny.height }, 40)
			.data,
	)

	const largest = sizes[sizes.length - 1]!
	return {
		width: largest.width,
		height: largest.height,
		blurhash,
		lqip: `data:image/jpeg;base64,${bytesToBase64(lqipBytes)}`,
		credits: exif.credits,
		files,
	}
}