imagestore

package module
v0.0.0-...-5f58e58 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 28, 2026 License: MIT Imports: 30 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

imagestore

Persistent image storage, thumbnail generation, and HTTP image serving for Go applications using sqlx.

imagestore accepts JPEG, PNG, HEIC/HEIF, and WebP uploads, converts every image to canonical WebP, assigns each image a stable ULID, stores bytes on the filesystem and identity/metadata in SQL, generates configured thumbnail variants asynchronously, reconciles missing thumbnails on startup, and serves images over HTTP by ID.

Module: github.com/smhanov/imagestore

Architecture overview

                  Submit / SubmitFile
                         |
                         v
              +-----------------------+
              | Decode + auto-orient  |
              | ConvertToWebP (VP8L)  |
              | preserve EXIF/XMP/ICC |
              +-----------------------+
                         |
          +--------------+--------------+
          |                             |
          v                             v
 originals/<id>.webp              thumbnail queue (bounded, 256)
 (atomic temp file + rename)             |
          |                      +------+------+
          v                      v             v
   images row (INSERT)      worker         worker  (DefaultThumbnailWorkers = 2)
                                     |
                                     v
                        thumbnails/<id>-<variant>.webp
                        (atomic temp file + rename, then UPSERT
                         image_thumbnails row)

Two owners, two stores:

  • Filesystem stores image bytes. The package owns <StorageFolder>/originals/ and <StorageFolder>/thumbnails/:
    • Canonical images: originals/<image-id>.webp
    • Thumbnails: thumbnails/<image-id>-<variant>.webp
  • SQL stores image identity and metadata. The package owns the images and image_thumbnails tables (created with CREATE TABLE IF NOT EXISTS via New). Applications store image_id values in their own tables.

Retrieval path:

GET /images/<id>?w=400&h=300
  -> Store.Handler() -> Store.BestRepresentation() (select only, never generates)
  -> Store.Open() / Store.OpenThumbnail() -> http.ServeContent
Design principles
  • Filesystem stores image bytes; SQL stores image identity and metadata.
  • Images are immutable after creation; IDs never depend on user-supplied filenames.
  • Thumbnail creation is asynchronous on a small bounded worker pool (default 2 workers, non-blocking enqueue). Failure to create a thumbnail never invalidates the original image.
  • Startup reconciliation makes thumbnail generation eventually consistent: every New() scans images x configured variants and queues missing/stale thumbnails without blocking.
  • Submit returns once the canonical WebP image and DB row are safely stored. It does not wait for thumbnails.
  • HTTP requests never dynamically resize images. They select from already-generated thumbnail variants.
  • No general job queue, distributed image-processing system, or CDN abstraction.

Prerequisites and installation

  • Go 1.26+ (module declares go 1.26.7).
  • No CGO / no libvips required. Pure-Go build:
    • Decode: stdlib image/jpeg, image/png + golang.org/x/image/webp + github.com/gen2brain/heic (HEVC in HEIF via bundled WASM run with wazero; uses system libheif via purego when available, otherwise falls back to WASM).
    • Encode: github.com/mayahiro/go-webp (VP8L lossless by default).
    • IDs: github.com/oklog/ulid/v2.
    • DB: github.com/jmoiron/sqlx with either modernc.org/sqlite (pure-Go SQLite) or github.com/jackc/pgx/v5 (PostgreSQL).
  • Optional: Docker + postgres:alpine only for running the PostgreSQL integration test (postgres_integration_test.go spins up an ephemeral container; it skips when IMAGSTORE_SKIP_POSTGRES=1 or Docker is unavailable).

Install:

go get github.com/smhanov/imagestore

Build / vet / test:

go build ./...
go vet ./...
go test ./...
# full suite with race detector (Postgres test skips without Docker):
go test -race ./...

SQLite usage (pure-Go, no setup):

import (
    "github.com/jmoiron/sqlx"
    _ "modernc.org/sqlite"
)

db, err := sqlx.Open("sqlite", "/var/lib/myapp/app.db")
if err != nil {
    // handle error
}
db.SetMaxOpenConns(1)
if _, err := db.Exec(`PRAGMA foreign_keys = ON`); err != nil {
    // handle error
}

PostgreSQL usage:

import (
    "github.com/jmoiron/sqlx"
    _ "github.com/jackc/pgx/v5/stdlib"
)

db, err := sqlx.Open("pgx", "postgres://user:secret@localhost:5432/myapp?sslmode=disable")
if err != nil {
    // handle error
}

Quickstart

package main

import (
    "context"
    "log"
    "os"

    "github.com/jmoiron/sqlx"
    _ "modernc.org/sqlite"

    "github.com/smhanov/imagestore"
)

func main() {
    db, err := sqlx.Open("sqlite", "/var/lib/myapp/app.db")
    if err != nil {
        log.Fatal(err)
    }
    db.SetMaxOpenConns(1)
    if _, err := db.Exec(`PRAGMA foreign_keys = ON`); err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    store, err := imagestore.New(db, imagestore.Config{
        StorageFolder: "/var/lib/myapp/images",
        Thumbnails: map[string]imagestore.ThumbnailConfig{
            "small":  {MaxWidth: 200, MaxHeight: 200},
            "medium": {MaxWidth: 800, MaxHeight: 800},
            "large":  {MaxWidth: 1600, MaxHeight: 1600},
        },
        ThumbnailWorkers: 2,
    })
    if err != nil {
        log.Fatal(err)
    }
    defer store.Close()

    ctx := context.Background()

    // Submit from a reader ...
    f, err := os.Open("photo.jpg")
    if err != nil {
        log.Fatal(err)
    }
    defer f.Close()
    img, err := store.Submit(ctx, f, imagestore.SubmitOptions{Filename: "photo.jpg"})
    if err != nil {
        log.Fatal(err)
    }

    // ... or directly from a file path (base name kept as display name).
    img2, err := store.SubmitFile(ctx, "photo.png")
    if err != nil {
        log.Fatal(err)
    }

    log.Printf("stored %s (%dx%d) and %s", img.ID, img.Width, img.Height, img2.ID)
}
Configuration
type Config struct {
    StorageFolder string
    Thumbnails map[string]ThumbnailConfig
    ThumbnailWorkers int
    Quality int // 0 = lossless (default), 1-100 = VP8 lossy for originals
}

type ThumbnailConfig struct {
    MaxWidth  int
    MaxHeight int
    Quality   int // 0 = use Config.Quality, 1-100 = VP8 lossy for this variant
}

Rules (Config.Validate, also enforced by New):

  • StorageFolder is required. New creates <StorageFolder>/originals and <StorageFolder>/thumbnails with os.MkdirAll.
  • Thumbnail names must match ^[a-zA-Z0-9_-]+$ (filesystem-safe identifiers).
  • MaxWidth and MaxHeight must both be > 0. They describe a bounding box: the thumbnail fits entirely inside, aspect ratio preserved, never stretched, never enlarged (images smaller than the box are returned unchanged).
  • Quality (on Config and on each variant) must be 0-100. 0 on a variant inherits Config.Quality; both 0 stays lossless.
  • ThumbnailWorkers <= 0 is normalized to DefaultThumbnailWorkers (const DefaultThumbnailWorkers = 2).

Full example (same as quickstart, with defaults noted):

store, err := imagestore.New(db, imagestore.Config{
    StorageFolder: "/var/lib/myapp/images",

    Thumbnails: map[string]imagestore.ThumbnailConfig{
        "small": {
            MaxWidth:  200,
            MaxHeight: 200,
        },
        "medium": {
            MaxWidth:  800,
            MaxHeight: 800,
        },
        "large": {
            MaxWidth:  1600,
            MaxHeight: 1600,
        },
    },

    ThumbnailWorkers: 2, // <= 0 also means 2
})

Filesystem layout

<storage>/
    originals/
    thumbnails/
  • Canonical: originals/<image-id>.webp
  • Thumbnails: thumbnails/<image-id>-<variant>.webp

Example:

/var/lib/myapp/images/
    originals/
        01K4F2Z6Q4A1YJ4TQBV8R7P89M.webp
    thumbnails/
        01K4F2Z6Q4A1YJ4TQBV8R7P89M-small.webp
        01K4F2Z6Q4A1YJ4TQBV8R7P89M-medium.webp
        01K4F2Z6Q4A1YJ4TQBV8R7P89M-large.webp

IDs are 26-character ULIDs (newID, time-sortable, URL-safe, filesystem-safe) and never depend on user-supplied filenames. SubmitOptions.Filename / Image.OriginalFilename is display-only metadata.

All file writes use temp-file-in-destination-dir + fsync + 0644 + atomic rename, so a partially written file never appears under its final name. Thumbnail DB rows are inserted/updated only after the rename succeeds.

Helpers:

func (s *Store) OriginalPath(id ID) string
func (s *Store) ThumbnailPath(id ID, variant string) string

Database schema

Owned tables, created idempotently by New via initSchema (CREATE TABLE IF NOT EXISTS). Exported DDL constants:

const SchemaImages = `CREATE TABLE IF NOT EXISTS images (...)`
const SchemaImageThumbnails = `CREATE TABLE IF NOT EXISTS image_thumbnails (...)`

All statements run through db.Rebind, so placeholders stay portable between SQLite (?) and PostgreSQL ($1).

images
CREATE TABLE IF NOT EXISTS images (
    id                  TEXT PRIMARY KEY,
    original_filename   TEXT,
    width               INTEGER NOT NULL,
    height              INTEGER NOT NULL,
    size_bytes          BIGINT NOT NULL,
    created_at          BIGINT NOT NULL
);
  • images.id is the stable externally referenceable image identifier. The canonical filename is derived from it (originals/<id>.webp) and is not stored separately.
  • width / height are canonical pixel dimensions after auto-orientation.
  • size_bytes is the canonical WebP byte length.
  • created_at stores Unix milliseconds (time.Now().UnixMilli(); read back with time.UnixMilli(...).UTC()).
  • size_bytes / created_at use BIGINT (64-bit); SQLite treats BIGINT with INTEGER affinity, so the schema is compatible with both SQLite and PostgreSQL.
image_thumbnails
CREATE TABLE IF NOT EXISTS image_thumbnails (
    image_id        TEXT NOT NULL,
    variant         TEXT NOT NULL,
    width           INTEGER NOT NULL,
    height          INTEGER NOT NULL,
    max_width       INTEGER NOT NULL,
    max_height      INTEGER NOT NULL,
    size_bytes      BIGINT NOT NULL,
    created_at      BIGINT NOT NULL,

    PRIMARY KEY (image_id, variant),

    FOREIGN KEY (image_id)
        REFERENCES images(id)
        ON DELETE CASCADE
);
  • width / height are the actual stored thumbnail dimensions, not just the configured maximums (selection uses these).
  • max_width / max_height record the configuration used to generate the thumbnail so startup reconciliation can detect config changes.
  • ON DELETE CASCADE removes thumbnail rows when the parent image row is deleted (Delete also removes the files).
Referencing images from application tables

Persist images.id in your own tables. SQLite example:

CREATE TABLE listings (
    id TEXT PRIMARY KEY,
    primary_image_id TEXT REFERENCES images(id)
);

Join-table example:

CREATE TABLE listing_images (
    listing_id TEXT NOT NULL,
    image_id TEXT NOT NULL REFERENCES images(id)
);

Notes:

  • In PostgreSQL the columns are typically TEXT REFERENCES images(id) the same way; add ON DELETE CASCADE / ON DELETE SET NULL to suit your lifecycle (Delete on the image cascades to image_thumbnails in all cases).
  • In SQLite, enable PRAGMA foreign_keys = ON per connection (it is per-connection; with SetMaxOpenConns(1) one exec covers the pool) or cascade deletes will not fire.

API reference

Package imagestore. Core lifecycle:

func New(db *sqlx.DB, config Config) (*Store, error)
func (s *Store) Close() error

New validates config, creates storage directories, creates tables idempotently, starts the thumbnail worker pool, and triggers startup reconciliation asynchronously (returns without waiting for thumbnails). Close gracefully halts workers (idempotent, nil-safe, does not close *sqlx.DB).

Submitting:

type SubmitOptions struct {
    Filename 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)

Submit reads (capped at 50 MiB), validates by content sniffing, decodes, auto-orients, converts to WebP, generates a ULID, atomically writes originals/<id>.webp, inserts the images row (removing the file on DB failure), queues one async job per configured variant, and returns the Image. Thumbnails are not awaited. SubmitFile opens the path and submits with Filename set to the base name.

Retrieval:

func (s *Store) Get(ctx context.Context, id ID) (*Image, error)
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)

Get returns metadata without loading bytes. Open / OpenThumbnail return readers for the canonical / variant files; callers need not know the layout. All check DB existence first and return ErrNotFound (wrapped) for unknown IDs or missing files.

Selection:

type Representation struct {
    ImageID ID
    Variant string
    Width  int
    Height int
    Original bool
}

func (s *Store) BestRepresentation(ctx context.Context, id ID, maxWidth int, maxHeight int) (*Representation, error)

Rules: both bounds <= 0 serves the original; otherwise only variants with both a DB row and a file on disk are considered, preferring the smallest thumbnail (by pixel area, tie-broken by smaller width then variant name) whose actual dimensions satisfy (maxWidth <= 0 || w >= maxWidth) && (maxHeight <= 0 || h >= maxHeight); if none satisfies, the largest available thumbnail is selected; if no thumbnails exist, the original is served. Never generates anything. Unknown images return ErrNotFound.

Deletion:

func (s *Store) Delete(ctx context.Context, id ID) error

Deletes the images row (cascading to image_thumbnails), then best-effort removes the original file plus every thumbnails/<id>-*.webp file. Unknown IDs return ErrNotFound.

Serving:

func (s *Store) Handler() http.Handler

See "HTTP handler" below.

Types, config, and errors:

type ID string

type Image struct {
    ID ID
    Width  int
    Height int
    SizeBytes int64
    OriginalFilename string
    CreatedAt time.Time
}

func (c *Config) Validate() error

const DefaultThumbnailWorkers = 2

var ErrNotFound = errors.New("imagestore: not found")
var ErrUnsupportedFormat = errors.New("imagestore: unsupported image format")
var ErrInvalidImage = errors.New("imagestore: invalid image")

Image engine (pure-Go; public so callers can reuse the pipeline):

type ImageFormat int

const (
    FormatUnknown ImageFormat = iota
    FormatJPEG
    FormatPNG
    FormatWebP
    FormatHEIC
)

func DetectFormat(data []byte) (ImageFormat, error)
func (f ImageFormat) String() string
func (f ImageFormat) MIMEType() string

type Metadata struct {
    EXIF        []byte
    XMP         []byte
    ICC         []byte
    Orientation int
}

type EncodeOptions struct {
    Lossy bool
    Quality int
}

type ConvertResult struct {
    Data []byte
    Width  int
    Height int
    Format ImageFormat
    Metadata Metadata
}

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 ConvertToWebP(data []byte) (*ConvertResult, error)
func ResizeToFit(img image.Image, maxW, maxH int) image.Image
func CreateThumbnail(data []byte, maxW, maxH int) (thumb []byte, width, height int, err error)
func CalculateBoundingBox(origW, origH, maxW, maxH int) (int, int)

DetectFormat sniffs JPEG (FF D8 FF), PNG magic, WebP (RIFF....WEBP), and HEIC/HEIF (ftyp brand) from contents only. DecodeImage returns ErrUnsupportedFormat for unknown inputs and ErrInvalidImage (wrapped) for corrupt inputs. EncodeWebP uses VP8L lossless by default; EncodeWebPWithOptions with Lossy: true selects VP8 lossy (Quality 1-100, <= 0 uses encoder default). ResizeToFit uses CatmullRom downsampling, never enlarges. CreateThumbnail intentionally strips metadata.

HTTP handler

Mount wherever desired; the handler expects the path to be /<image-id> relative to the mount point:

mux.Handle("/images/", http.StripPrefix(
    "/images/",
    store.Handler(),
))

URLs:

/images/01K4F2Z6Q4A1YJ4TQBV8R7P89M
/images/01K4F2Z6Q4A1YJ4TQBV8R7P89M?w=400&h=300
/images/01K4F2Z6Q4A1YJ4TQBV8R7P89M.webp?w=400

Behavior:

  • Path: leading/trailing slashes trimmed; optional .webp suffix stripped; nested paths (a/b) rejected with 400; empty IDs or IDs outside [A-Za-z0-9_-] rejected with 400.
  • Query: w and h are optional integer bounds (empty means 0 = unbounded); non-numeric or negative values yield 400.
  • Methods: only GET and HEAD; anything else yields 405 with Allow: GET, HEAD.
  • Selection delegates to BestRepresentation and never generates thumbnails.
  • Responses carry Content-Type: image/webp, Content-Length, and Cache-Control: public, max-age=31536000, immutable (safe: IDs are never reused), served via http.ServeContent, so Range requests, HEAD semantics, and conditional requests work.
  • Unknown images yield 404; unexpected failures yield 500.

Selection examples (variants small 200x200, medium 800x800, large 1600x1600):

Request Serves
(no params) original
w=150&h=150 small
w=500&h=500 medium
w=1200&h=800 large
w=3000&h=3000 largest available thumbnail

Thumbnail rules and reconciliation

  • Each variant fits inside its MaxWidth x MaxHeight box with aspect ratio preserved (see CalculateBoundingBox: already-fitting images unchanged, otherwise scale = min(maxW/origW, maxH/origH), rounded, min 1px). Example: 4000x3000 with 800x800 yields 800x600; 1000x4000 yields 200x800.
  • Thumbnails are WebP (CreateThumbnail), downsampled with CatmullRom, and intentionally carry no metadata; the canonical image is authoritative.
  • Workers: bounded pool (ThumbnailWorkers, default 2), queue size 256, non-blocking enqueue with background-goroutine fallback; Submit never blocks on thumbnails; job failures are logged and isolated.
  • Startup reconciliation (New -> go reconcile()): for every images row x every configured variant, checks (1) image_thumbnails row exists, (2) file exists, (3) max_width matches config, (4) max_height matches config; queues regeneration on any failure; never blocks New; never deletes originals. Removed variants are left in place (files + rows) per spec; a later maintenance pass may clean them.

Metadata preservation

  • Extracted at decode: JPEG APP1 EXIF / APP1 XMP / APP2 ICC (multi-segment reassembly), PNG eXIf / iTXt XML:com.adobe.xmp / iCCP, WebP EXIF / XMP / ICCP chunks, HEIC meta box Exif item (TIFF profile). Unparsable sections contribute nothing; extraction never fails the submit.
  • Preserved by muxing raw EXIF / XMP / ICC payloads into the WebP extended container on encode (EncodeWebP / EncodeWebPWithOptions).
  • Orientation: JPEG and HEIC decoders do not apply EXIF orientation themselves (the HEIC decoder does apply the container irot/imir transformative properties), so DecodeImage rotates/flips pixels per the EXIF orientation tag (1-8) and normalizes the stored EXIF tag to 1. Output pixels always display with the intended orientation.
  • Metadata with no WebP equivalent is discarded. Thumbnails intentionally carry no metadata.
  • WebP limitations: only still images; no animation support; encoder default is VP8L lossless (exact pixels, larger files) unless EncodeOptions{Lossy: true} is used explicitly. The Submit path uses lossless by default and VP8 lossy when Config.Quality is 1-100; thumbnails follow their variant Quality, falling back to Config.Quality.
  • HEIC notes: still images only (sequences decode the primary frame); EXIF is preserved, XMP/ICC extraction for HEIC is not implemented; the decoder applies irot/imir and the engine applies EXIF orientation on top, so files carrying the same rotation in both places observe both (matching the JPEG-style pipeline).

Supported formats and errors

Detection is content-based (magic bytes), never filename or Content-Type:

Format Detect Decode Notes
JPEG yes yes EXIF/XMP/ICC extracted; orientation applied
PNG yes yes eXIf / iTXt XMP / iCCP extracted
WebP yes yes still images; EXIF / XMP / ICCP round-tripped
HEIC/HEIF yes yes heic/heix/heim/heis/hevc/hevx/mif1/msf1; EXIF extracted; orientation applied; stills only
other no no ErrUnsupportedFormat
var ErrNotFound = errors.New("imagestore: not found")                 // unknown image/thumbnail
var ErrUnsupportedFormat = errors.New("imagestore: unsupported image format")
var ErrInvalidImage = errors.New("imagestore: invalid image")         // corrupt payload

Corrupt inputs that claim a supported format wrap ErrInvalidImage (check with errors.Is). Empty submits return ErrUnsupportedFormat; oversized submits (> 50 MiB) return ErrInvalidImage.

Testing

go test ./...
go test -v -race ./...
IMAGSTORE_SKIP_POSTGRES=1 go test ./...   # skip Docker-backed Postgres test

SQLite tests use modernc.org/sqlite with SetMaxOpenConns(1), PRAGMA foreign_keys=ON, busy_timeout=5000, and WAL for file-backed DBs. The Postgres integration test starts an ephemeral postgres:alpine container and skips when Docker is unavailable.

License

MIT — see LICENSE.

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

View Source
const DefaultThumbnailWorkers = 2

DefaultThumbnailWorkers is used when Config.ThumbnailWorkers <= 0.

View Source
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.

View Source
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/"".

View Source
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

View Source
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

func CalculateBoundingBox(origW, origH, maxW, maxH int) (int, int)

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

func CreateThumbnail(data []byte, maxW, maxH int) (thumb []byte, width, height int, err error)

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

func DecodeImage(data []byte) (image.Image, ImageFormat, Metadata, error)

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

func EncodeWebP(img image.Image, md Metadata) ([]byte, error)

EncodeWebP encodes img to canonical WebP bytes with lossless (VP8L) encoding, attaching EXIF/XMP/ICC metadata when present.

func EncodeWebPWithOptions

func EncodeWebPWithOptions(img image.Image, md Metadata, opts EncodeOptions) ([]byte, error)

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

func ResizeToFit(img image.Image, maxW, maxH int) image.Image

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

func (c *Config) Validate() error

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

type Metadata struct {
	EXIF        []byte
	XMP         []byte
	ICC         []byte
	Orientation int
}

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

type Representation struct {
	ImageID ID

	Variant string

	Width  int
	Height int

	Original bool
}

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

func New(db *sqlx.DB, config Config) (*Store, error)

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

func (s *Store) Close() error

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

func (s *Store) Delete(ctx context.Context, id ID) error

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

func (s *Store) Get(ctx context.Context, id ID) (*Image, error)

Get returns the *Image metadata for id without loading image bytes. It returns ErrNotFound when no such image exists.

func (*Store) Handler

func (s *Store) Handler() http.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

func (s *Store) Open(ctx context.Context, id ID) (io.ReadCloser, error)

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

func (s *Store) OpenThumbnail(ctx context.Context, id ID, variant string) (io.ReadCloser, error)

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

func (s *Store) OriginalPath(id ID) string

OriginalPath returns the canonical filesystem path for an image: <StorageFolder>/originals/<id>.webp.

func (*Store) Submit

func (s *Store) Submit(ctx context.Context, r io.Reader, opts SubmitOptions) (*Image, error)

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

func (s *Store) SubmitFile(ctx context.Context, filename string) (*Image, error)

SubmitFile opens the file at filename and submits its contents. The path's base name is retained as SubmitOptions.Filename.

func (*Store) ThumbnailPath

func (s *Store) ThumbnailPath(id ID, variant string) string

ThumbnailPath returns the filesystem path for a thumbnail variant: <StorageFolder>/thumbnails/<id>-<variant>.webp.

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址