Documentation
¶
Overview ¶
Package imagestore provides persistent image storage, thumbnail generation, and HTTP image serving.
images.id is the stable externally referenceable image identifier. Applications may persist this ID in their own tables, e.g.:
CREATE TABLE listings (
id TEXT PRIMARY KEY,
primary_image_id TEXT REFERENCES images(id)
);
Index ¶
- Constants
- Variables
- func CalculateBoundingBox(origW, origH, maxW, maxH int) (int, int)
- func CreateThumbnail(data []byte, maxW, maxH int) (thumb []byte, width, height int, err error)
- func CreateThumbnailWithOptions(data []byte, maxW, maxH int, opts EncodeOptions) (thumb []byte, width, height int, err error)
- func DecodeImage(data []byte) (image.Image, ImageFormat, Metadata, error)
- func EncodeWebP(img image.Image, md Metadata) ([]byte, error)
- func EncodeWebPWithOptions(img image.Image, md Metadata, opts EncodeOptions) ([]byte, error)
- func ResizeToFit(img image.Image, maxW, maxH int) image.Image
- type Config
- type ConvertResult
- type EncodeOptions
- type ID
- type Image
- type ImageFormat
- type Metadata
- type Representation
- type Store
- func (s *Store) BestRepresentation(ctx context.Context, id ID, maxWidth int, maxHeight int) (*Representation, error)
- func (s *Store) Close() error
- func (s *Store) Delete(ctx context.Context, id ID) error
- func (s *Store) Get(ctx context.Context, id ID) (*Image, error)
- func (s *Store) Handler() http.Handler
- func (s *Store) Open(ctx context.Context, id ID) (io.ReadCloser, error)
- func (s *Store) OpenThumbnail(ctx context.Context, id ID, variant string) (io.ReadCloser, error)
- func (s *Store) OriginalPath(id ID) string
- func (s *Store) Submit(ctx context.Context, r io.Reader, opts SubmitOptions) (*Image, error)
- func (s *Store) SubmitFile(ctx context.Context, filename string) (*Image, error)
- func (s *Store) ThumbnailPath(id ID, variant string) string
- type SubmitOptions
- type ThumbnailConfig
Constants ¶
const DefaultThumbnailWorkers = 2
DefaultThumbnailWorkers is used when Config.ThumbnailWorkers <= 0.
const SchemaImageThumbnails = `` /* 466-byte string literal not displayed */
SchemaImageThumbnails creates the image_thumbnails table. max_width/max_height record the configuration used to generate the thumbnail so startup reconciliation can detect config changes.
const SchemaImages = `` /* 305-byte string literal not displayed */
SchemaImages creates the images table. images.id is the stable externally referenceable image identifier. images.hash stores the hex-encoded SHA-256 over the submitted original photo bytes and is used for exact-byte deduplication (T009). It is nullable so legacy rows created before T009 scan as NULL/"".
const SchemaImagesHashIndex = `CREATE UNIQUE INDEX IF NOT EXISTS idx_images_hash ON images (hash);`
SchemaImagesHashIndex deduplicates submissions via exact-byte match. UNIQUE guarantees concurrent inserts of identical bytes collide so Submit can safely return the existing row. Multiple NULLs (legacy rows) are allowed by both SQLite and PostgreSQL.
Variables ¶
var ( // ErrNotFound is returned when an image or thumbnail does not exist. ErrNotFound = errors.New("imagestore: not found") // ErrUnsupportedFormat is returned when input bytes are not a // supported image format. Format detection is based on file // contents, not filename extension or Content-Type. ErrUnsupportedFormat = errors.New("imagestore: unsupported image format") // ErrInvalidImage is returned when input bytes claim a supported // format but are corrupt or otherwise undecodable. ErrInvalidImage = errors.New("imagestore: invalid image") )
Functions ¶
func CalculateBoundingBox ¶
CalculateBoundingBox fits an origW x origH image inside a maxW x maxH bounding box while preserving the aspect ratio.
- If the image already fits (origW <= maxW && origH <= maxH) it is returned unchanged: images are never enlarged.
- Otherwise the result is (round(origW*scale), round(origH*scale)) with scale = min(maxW/origW, maxH/origH), so the image fits entirely inside the box without stretching. Each dimension is clamped to a minimum of 1 pixel.
- Non-positive inputs cannot describe a box; they yield (0, 0).
func CreateThumbnail ¶
CreateThumbnail decodes data, fits it inside the maxW x maxH bounding box, and encodes the result as lossless WebP. It returns the thumbnail bytes and their dimensions. Thumbnails intentionally carry no metadata; the canonical image is the authoritative metadata-preserving version.
func CreateThumbnailWithOptions ¶
func CreateThumbnailWithOptions(data []byte, maxW, maxH int, opts EncodeOptions) (thumb []byte, width, height int, err error)
CreateThumbnailWithOptions is CreateThumbnail with an explicit encoding, e.g. lossyOptions(variantQuality) for smaller thumbnails.
func DecodeImage ¶
DecodeImage sniffs the input format, decodes the pixels, extracts available EXIF/XMP/ICC metadata, and applies EXIF auto-orientation.
Unrecognized inputs return ErrUnsupportedFormat; inputs that claim a supported format but fail to decode return ErrInvalidImage.
func EncodeWebP ¶
EncodeWebP encodes img to canonical WebP bytes with lossless (VP8L) encoding, attaching EXIF/XMP/ICC metadata when present.
func EncodeWebPWithOptions ¶
EncodeWebPWithOptions encodes img to WebP bytes per opts, attaching EXIF/XMP/ICC metadata when present. Metadata payloads are written verbatim into the extended-container chunks.
func ResizeToFit ¶
ResizeToFit downsamples img to fit inside the maxW x maxH bounding box using high-quality filtering (CatmullRom), preserving the aspect ratio. Images that already fit are returned unchanged (never enlarged); invalid bounds also return the input unchanged.
Types ¶
type Config ¶
type Config struct {
// StorageFolder is the root directory for image files. Required.
// The Store owns <StorageFolder>/originals and
// <StorageFolder>/thumbnails beneath it.
StorageFolder string
// Thumbnails maps filesystem-safe variant names to their bounding
// boxes.
Thumbnails map[string]ThumbnailConfig
// ThumbnailWorkers bounds the async thumbnail worker pool.
// Values <= 0 are normalized to DefaultThumbnailWorkers.
ThumbnailWorkers int
// Quality selects VP8 lossy encoding at 1-100 for canonical
// originals written by Submit. 0 keeps the historical VP8L
// lossless behavior.
Quality int
}
Config configures a Store.
func (*Config) Validate ¶
Validate checks the configuration and normalizes defaults.
It rejects a missing StorageFolder, non-filesystem-safe thumbnail variant names, non-positive MaxWidth/MaxHeight values, and Quality values outside 0-100. A ThumbnailWorkers value <= 0 is normalized to DefaultThumbnailWorkers.
type ConvertResult ¶
type ConvertResult struct {
// Data holds the canonical WebP bytes (RIFF....WEBP).
Data []byte
// Width and Height are the canonical pixel dimensions after
// auto-orientation.
Width int
Height int
// Format is the sniffed source format.
Format ImageFormat
// Metadata carries the preserved EXIF/XMP/ICC payloads. When EXIF was
// present its orientation tag is normalized to 1 because the rotation
// has already been applied to the pixels.
Metadata Metadata
}
ConvertResult is the canonical WebP image produced by ConvertToWebP.
func ConvertToWebP ¶
func ConvertToWebP(data []byte) (*ConvertResult, error)
ConvertToWebP runs the canonical image-processing path: sniff the source format, decode, auto-orient, and encode to WebP with metadata preserved. The output is VP8L lossless.
func ConvertToWebPWithOptions ¶
func ConvertToWebPWithOptions(data []byte, opts EncodeOptions) (*ConvertResult, error)
ConvertToWebPWithOptions is ConvertToWebP with an explicit encoding, e.g. lossyOptions(storeQuality) for smaller photographic originals.
type EncodeOptions ¶
type EncodeOptions struct {
// Lossy selects VP8 lossy encoding instead of VP8L lossless.
Lossy bool
// Quality controls VP8 lossy quality from 1 to 100. Values <= 0 use
// the encoder default; values > 100 are clamped. Ignored unless
// Lossy is true.
Quality int
}
EncodeOptions tunes WebP encoding. The zero value selects VP8L lossless encoding, which preserves every pixel exactly.
type ID ¶
type ID string
ID is the stable, externally referenceable image identifier.
IDs are URL-safe and filesystem-safe and never depend on user-supplied filenames. Image IDs are permanent and images are immutable after creation.
type Image ¶
type Image struct {
ID ID
Width int
Height int
SizeBytes int64
OriginalFilename string
// Hash is the hex-encoded SHA-256 over the submitted original photo
// bytes, used for exact-byte deduplication. Empty ("") for legacy
// rows created before the T009 migration.
Hash string
CreatedAt time.Time
}
Image describes a stored canonical image.
The canonical file bytes live on the filesystem at <StorageFolder>/originals/<id>.webp and are derived from ID, so the filename does not need to be stored separately. OriginalFilename retains the user-supplied name for display purposes only.
type ImageFormat ¶
type ImageFormat int
ImageFormat identifies an image container format sniffed from file contents. Detection is content-based (magic bytes); it never consults filename extensions or HTTP Content-Type headers.
const ( // FormatUnknown is returned together with ErrUnsupportedFormat when // DetectFormat cannot recognize the input bytes. FormatUnknown ImageFormat = iota // FormatJPEG is a JPEG bitstream (SOI marker 0xFF 0xD8 0xFF). FormatJPEG // FormatPNG is a PNG bitstream (magic 89 50 4E 47 0D 0A 1A 0A). FormatPNG // FormatWebP is a WebP bitstream (RIFF....WEBP container). FormatWebP // FormatHEIC covers HEIC and HEIF inputs: an ISO Base Media File // Format (ISOBMFF) container whose ftyp box names a HEVC still-image // brand (heic, heix, heim, heis, hevc, hevx) or a generic HEIF brand // (mif1, msf1). FormatHEIC )
func DetectFormat ¶
func DetectFormat(data []byte) (ImageFormat, error)
DetectFormat sniffs the image format from raw file bytes.
It recognizes JPEG (FF D8 FF), PNG (89 50 4E 47 0D 0A 1A 0A), WebP (RIFF....WEBP), and HEIC/HEIF (an ftyp box naming a HEVC/HEIF brand). Anything else — including empty or truncated inputs — returns FormatUnknown with ErrUnsupportedFormat.
func (ImageFormat) MIMEType ¶
func (f ImageFormat) MIMEType() string
MIMEType returns the IANA media type for the format, or an empty string for FormatUnknown.
func (ImageFormat) String ¶
func (f ImageFormat) String() string
String returns a short lowercase name for the format.
type Metadata ¶
Metadata carries image metadata extracted at decode time.
EXIF holds the raw TIFF profile (starting with the II or MM byte-order marker, without the JPEG "Exif\0\0" prefix), XMP holds the raw XMP packet, and ICC holds the raw ICC color profile. The payloads are stored verbatim in the corresponding WebP container chunks on encode, so they use the same representation the WebP chunks require.
Orientation is the EXIF orientation tag (1-8) found in the source, or 1 when the source carries no orientation. The engine applies the rotation to the decoded pixels and normalizes the stored EXIF tag to 1, so the pixels always display with the intended orientation.
type Representation ¶
Representation describes the best available stored file for requested dimensions.
When Original is true, Variant is empty and Width/Height describe the canonical image. Otherwise Variant names the thumbnail variant and Width/Height are the actual stored thumbnail dimensions (not merely the configured maximums).
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store owns image storage: filesystem bytes plus SQL metadata.
The filesystem holds image bytes under <StorageFolder>/originals and <StorageFolder>/thumbnails; SQL holds image identity and metadata.
Thumbnail generation runs on a bounded async worker pool (see worker.go) with startup reconciliation (see reconcile.go). Submit returns once the canonical image and DB row are stored; thumbnails are eventually consistent. Close halts the workers.
func New ¶
New validates configuration, creates the required storage directories, and creates the required database tables idempotently.
It creates <StorageFolder>/originals and <StorageFolder>/thumbnails with os.MkdirAll and executes CREATE TABLE IF NOT EXISTS for the images and image_thumbnails tables. It starts the bounded thumbnail worker pool and triggers startup reconciliation asynchronously without blocking: New returns once the canonical storage is ready, thumbnails are eventually consistent.
func (*Store) BestRepresentation ¶
func (s *Store) BestRepresentation(ctx context.Context, id ID, maxWidth int, maxHeight int) (*Representation, error)
BestRepresentation selects the best already-generated file for the requested bounds without generating anything.
Rules (specs.md section 18):
- If neither maxWidth nor maxHeight is requested (both <= 0), serve original.
- Consider only thumbnail variants that currently exist for the image: a row in image_thumbnails AND a file on disk.
- Prefer the smallest thumbnail whose dimensions satisfy the requested bounds: (maxWidth <= 0 || w >= maxWidth) && (maxHeight <= 0 || h >= maxHeight). Smallest means smallest pixel area (w*h), tie-broken by smaller width, then lexicographically smaller variant for determinism.
- If no thumbnail satisfies the bounds, select the largest available thumbnail (largest area, tie-broken by larger width).
- If no thumbnails exist, serve the original.
- Never generate a thumbnail synchronously.
It returns ErrNotFound (wrapped) when the image does not exist.
func (*Store) Close ¶
Close gracefully halts the thumbnail workers and releases resources.
It is idempotent and safe to call twice or on a nil Store. It signals workers to stop and waits for in-flight jobs to finish; queued but unstarted jobs are discarded. It does not close the underlying *sqlx.DB.
func (*Store) Delete ¶
Delete removes the images row for id (cascading to image_thumbnails via ON DELETE CASCADE) and deletes the original file plus every thumbnail file matching thumbnails/<id>-*.webp.
It returns ErrNotFound when the image ID does not exist. File cleanup is best-effort: missing files after a successful DB delete are ignored, but all matching files are attempted so no orphan bytes remain.
func (*Store) Get ¶
Get returns the *Image metadata for id without loading image bytes. It returns ErrNotFound when no such image exists.
func (*Store) Handler ¶
Handler returns an http.Handler serving images by ID.
The handler expects the request path to be /<image-id> relative to where the application mounts it, e.g.:
mux.Handle("/images/", http.StripPrefix("/images/", store.Handler()))
Path handling:
- Leading and trailing slashes are trimmed.
- An optional ".webp" suffix is stripped (e.g. /<id>.webp).
- Paths containing "/" after trimming (nested paths) are rejected with 400.
- Empty IDs or IDs with characters outside [A-Za-z0-9_-] are rejected with 400.
Query parameters:
- "w" and "h" are optional integer bounds. Empty means 0 (unbounded). Non-numeric or negative values yield 400.
Method handling:
- Only GET and HEAD are allowed; anything else yields 405 with an Allow header.
Representation selection delegates to BestRepresentation (never generates thumbnails). Responses carry Content-Type image/webp, Content-Length, and Cache-Control, and are served via http.ServeContent so Range requests, HEAD semantics, and conditional requests work. Unknown images yield 404; unexpected failures yield 500.
func (*Store) Open ¶
Open returns an io.ReadCloser for originals/<id>.webp. It checks DB existence first so unknown IDs return ErrNotFound even if a stray file exists, and maps missing files to ErrNotFound as well.
func (*Store) OpenThumbnail ¶
OpenThumbnail returns an io.ReadCloser for thumbnails/<id>-<variant>.webp. It checks DB existence first, then maps a missing thumbnail file to ErrNotFound. Thumbnails are generated asynchronously, so a missing file for a known image is expected until workers (T004) produce it.
func (*Store) OriginalPath ¶
OriginalPath returns the canonical filesystem path for an image: <StorageFolder>/originals/<id>.webp.
func (*Store) Submit ¶
Submit reads an image, converts it to canonical WebP, persists it atomically under originals/<id>.webp, inserts the images row, queues thumbnail generation, and returns the Image metadata.
It performs synchronously steps 1-9 of specs.md section 8 and returns once the canonical image and DB row are safely stored; it does not wait for thumbnails to finish.
func (*Store) SubmitFile ¶
SubmitFile opens the file at filename and submits its contents. The path's base name is retained as SubmitOptions.Filename.
type SubmitOptions ¶
type SubmitOptions struct {
Filename string
}
SubmitOptions tunes Submit. Filename is retained as display-only metadata (Image.OriginalFilename); it is never used as a storage filename.
type ThumbnailConfig ¶
type ThumbnailConfig struct {
MaxWidth int
MaxHeight int
// Quality selects VP8 lossy encoding at 1-100 for this variant.
// 0 means "use Config.Quality" (and if that is also 0, stay
// lossless like before).
Quality int
}
ThumbnailConfig describes the bounding box for one thumbnail variant.
The generated thumbnail fits entirely inside the MaxWidth x MaxHeight box with aspect ratio preserved. Images are never stretched or enlarged.