imagor

package module
v1.8.5 Latest Latest
Warning

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

Go to latest
Published: Apr 11, 2026 License: Apache-2.0 Imports: 24 Imported by: 9

README

imagor

Test Status Codecov Docker Hub Docs

imagor is a fast, secure image processing server and Go library.

imagor uses one of the most efficient image processing libraries libvips with Go binding vipsgen — also available for low-level libvips operations directly in Go. It is typically 4-8x faster than using the quickest ImageMagick settings. imagor implements libvips streaming that facilitates parallel processing pipelines, achieving high network throughput.

imagor features a ton of image processing use cases, available as a HTTP server with first-class Docker support. It adopts the thumbor URL syntax representing a high-performance drop-in replacement.

imagor is built with speed, security and extensibility in mind. Alongside there is imagorvideo bringing video thumbnail capability through ffmpeg C bindings.

Quick Start
docker run -p 8000:8000 shumc/imagor -imagor-unsafe -imagor-auto-webp

Original images:

https://raw.githubusercontent.com/cshum/imagor/master/testdata/gopher.png
https://raw.githubusercontent.com/cshum/imagor/master/testdata/dancing-banana.gif
https://raw.githubusercontent.com/cshum/imagor/master/testdata/gopher-front.png

Try out the following image URLs:

http://localhost:8000/unsafe/fit-in/200x200/filters:fill(white)/https://raw.githubusercontent.com/cshum/imagor/master/testdata/gopher.png
http://localhost:8000/unsafe/200x200/smart/filters:fill(white):format(jpeg):quality(80)/https://raw.githubusercontent.com/cshum/imagor/master/testdata/gopher.png
http://localhost:8000/unsafe/fit-in/-180x180/10x10/filters:hue(290):saturation(100):fill(yellow)/raw.githubusercontent.com/cshum/imagor/master/testdata/gopher.png
http://localhost:8000/unsafe/30x40:100x150/filters:fill(cyan)/raw.githubusercontent.com/cshum/imagor/master/testdata/dancing-banana.gif
http://localhost:8000/unsafe/fit-in/200x150/filters:fill(yellow):watermark(raw.githubusercontent.com/cshum/imagor/master/testdata/gopher-front.png,repeat,bottom,0,40,40)/raw.githubusercontent.com/cshum/imagor/master/testdata/dancing-banana.gif

[!TIP] Full documentation at docs.imagor.netImage Endpoint · Filters · Storage · Security · Configuration

Documentation

Index

Constants

View Source
const Version = "1.8.5"

Version imagor version

Variables

View Source
var (
	// ErrNotFound not found error
	ErrNotFound = NewError("not found", http.StatusNotFound)
	// ErrInvalid syntactic invalid path error
	ErrInvalid = NewError("invalid", http.StatusBadRequest)
	// ErrMethodNotAllowed method not allowed error
	ErrMethodNotAllowed = NewError("method not allowed", http.StatusMethodNotAllowed)
	// ErrSourceNotAllowed http source not allowed error
	ErrSourceNotAllowed = NewError("http source not allowed", http.StatusForbidden)
	// ErrSignatureMismatch URL signature mismatch error
	ErrSignatureMismatch = NewError("url signature mismatch", http.StatusForbidden)
	// ErrTimeout timeout error
	ErrTimeout = NewError("timeout", http.StatusRequestTimeout)
	// ErrExpired expire error
	ErrExpired = NewError("expired", http.StatusGone)
	// ErrUnsupportedFormat unsupported format error
	ErrUnsupportedFormat = NewError("unsupported format", http.StatusNotAcceptable)
	// ErrMaxSizeExceeded maximum size exceeded error
	ErrMaxSizeExceeded = NewError("maximum size exceeded", http.StatusBadRequest)
	// ErrMaxResolutionExceeded maximum resolution exceeded error
	ErrMaxResolutionExceeded = NewError("maximum resolution exceeded", http.StatusUnprocessableEntity)
	// ErrTooManyRequests too many requests error
	ErrTooManyRequests = NewError("too many requests", http.StatusTooManyRequests)
	// ErrInternal internal error
	ErrInternal = NewError("internal error", http.StatusInternalServerError)
)

Functions

This section is empty.

Types

type Blob added in v0.6.0

type Blob struct {
	Header http.Header
	Stat   *Stat
	// contains filtered or unexported fields
}

Blob imagor data blob abstraction

func NewBlob added in v0.9.0

func NewBlob(newReader func() (reader io.ReadCloser, size int64, err error)) *Blob

NewBlob creates imagor Blob from io.ReadCloser and size

func NewBlobFromBytes added in v0.9.0

func NewBlobFromBytes(buf []byte) *Blob

NewBlobFromBytes creates imagor Blob from []byte buffer

func NewBlobFromFile added in v1.0.0

func NewBlobFromFile(filepath string, checks ...func(os.FileInfo) error) *Blob

NewBlobFromFile creates imagor Blob from file path and optional file info checks

func NewBlobFromJsonMarshal added in v1.0.0

func NewBlobFromJsonMarshal(v any) *Blob

NewBlobFromJsonMarshal creates imagor Blob from json marshal of any object

func NewBlobFromMemory added in v1.1.1

func NewBlobFromMemory(buf []byte, width, height, bands int) *Blob

NewBlobFromMemory creates imagor Blob from raw RGB/RGBA buffer

func NewEmptyBlob added in v0.9.0

func NewEmptyBlob() *Blob

NewEmptyBlob creates empty imagor Blob

func (*Blob) BlobType added in v0.8.19

func (b *Blob) BlobType() BlobType

BlobType returns BlobType

func (*Blob) ContentType added in v0.9.0

func (b *Blob) ContentType() string

ContentType returns content type

func (*Blob) Err added in v0.9.0

func (b *Blob) Err() error

Err returns Blob error

func (*Blob) FilePath added in v0.6.0

func (b *Blob) FilePath() string

FilePath returns Blob file path if blob is created from file

func (*Blob) IsEmpty added in v0.6.0

func (b *Blob) IsEmpty() bool

IsEmpty check if blob is empty

func (*Blob) IsRaw added in v1.7.3

func (b *Blob) IsRaw() bool

IsRaw check if blob is a camera RAW image format

func (*Blob) Memory added in v1.1.1

func (b *Blob) Memory() (data []byte, width, height, bands int, ok bool)

Memory returns memory data if Blob is created from memory

func (*Blob) NewReadSeeker added in v1.1.0

func (b *Blob) NewReadSeeker() (io.ReadSeekCloser, int64, error)

NewReadSeeker create read seeker if reader supports seek, or attempts to simulate seek using memory or temp file buffer

func (*Blob) NewReader added in v0.9.0

func (b *Blob) NewReader() (reader io.ReadCloser, size int64, err error)

NewReader creates new io.ReadCloser and returns size if known

func (*Blob) ReadAll added in v0.6.0

func (b *Blob) ReadAll() ([]byte, error)

ReadAll real all bytes from Blob

func (*Blob) Release added in v1.6.0

func (b *Blob) Release() error

Release stops reading from the source early and releases resources. This is safe to call multiple times and from multiple goroutines. Only works for blobs that use fanoutreader (when fanout is enabled).

func (*Blob) SetContentType added in v1.0.0

func (b *Blob) SetContentType(contentType string)

SetContentType set Blob content type. which overrides default sniffing if this is set

func (*Blob) Size added in v1.0.0

func (b *Blob) Size() int64

Size returns Blob size if known

func (*Blob) Sniff added in v0.9.5

func (b *Blob) Sniff() []byte

Sniff returns first 512 bytes of blob data for type sniffing

func (*Blob) SupportsAnimation added in v0.8.0

func (b *Blob) SupportsAnimation() bool

SupportsAnimation check if blob supports animation

type BlobType added in v0.8.19

type BlobType int

BlobType blob content type

const (
	BlobTypeUnknown BlobType = iota
	BlobTypeEmpty
	BlobTypeMemory
	BlobTypeJSON
	BlobTypeJPEG
	BlobTypePNG
	BlobTypeGIF
	BlobTypeWEBP
	BlobTypeJXL
	BlobTypeAVIF
	BlobTypeHEIF
	BlobTypeTIFF
	BlobTypeJP2
	BlobTypeBMP
	BlobTypePDF
	BlobTypeSVG
	BlobTypeRAF
	BlobTypeORF
	BlobTypeRW2
	BlobTypeX3F
	BlobTypeCR3
	BlobTypeCR2
)

BlobType enum

type Cacher added in v1.7.3

type Cacher interface {
	LoadFromCache(key string, w, h int) (*Blob, bool)
}

Cacher is an optional Processor interface for in-memory blob caching. LoadFromCache is called by imagor.Do() before loadStorage; on a hit the cached blob is passed directly to Process(), skipping loader/storage I/O entirely.

w and h are the requested output dimensions used to determine cache eligibility, not to select a blob of that size. Return (nil, false) when w or h is zero (unknown size) or exceeds the cache budget — the cache holds a single downscaled copy per image path and cannot safely serve those requests.

type Detector added in v1.8.0

type Detector interface {
	Startup(ctx context.Context) error
	Detect(ctx context.Context, imagePath string, blob *Blob) ([]DetectorRegion, error)
	Shutdown(ctx context.Context) error
}

Detector detects regions of interest in a raw pixel buffer. Implementations are free to perform any kind of detection (faces, objects, text boxes, etc.) — the only contract is the coordinate space.

imagePath identifies the source image (e.g. URL path) and is used as a cache key by implementations that cache results. Pass an empty string to opt out of caching for a particular call.

blob must be a BlobTypeMemory blob created with NewBlobFromMemory, carrying row-major sRGB/sRGBA pixels. Retrieve dimensions via blob.Memory().

Returned regions must use normalised coordinates in [0.0, 1.0] relative to the image width / height stored in blob.

type DetectorAdder added in v1.8.0

type DetectorAdder interface {
	AddDetector(Detector)
}

DetectorAdder is implemented by processors that accept one or more Detectors. imagorface and other detector plugins use this interface to wire a detector into a processor without importing the processor package directly.

type DetectorRegion added in v1.8.0

type DetectorRegion struct {
	Left, Top, Right, Bottom float64
	Score                    float64 // detection confidence; 0 means not provided
	Name                     string  // class name e.g. "face"; empty means not provided
}

DetectorRegion is a normalised bounding box where all fields are ratios in [0.0, 1.0] relative to the image dimensions passed to Detector.Detect.

type ErrForward added in v1.1.0

type ErrForward struct {
	imagorpath.Params
}

ErrForward indicator passing imagorpath.Params to next processor

func (ErrForward) Error added in v1.1.0

func (p ErrForward) Error() string

Error implements error

type Error

type Error struct {
	Message string `json:"message,omitempty"`
	Code    int    `json:"status,omitempty"`
}

Error imagor error convention

func NewError

func NewError(msg string, code int) Error

NewError creates imagor Error from message and status code

func NewErrorFromStatusCode

func NewErrorFromStatusCode(code int) Error

NewErrorFromStatusCode creates imagor Error solely from status code

func WrapError

func WrapError(err error) Error

WrapError wraps Go error into imagor Error

func (Error) Error

func (e Error) Error() string

Error implements error

func (Error) Timeout added in v0.3.0

func (e Error) Timeout() bool

Timeout indicates if error is timeout

type Imagor

type Imagor struct {
	Unsafe                 bool
	Signer                 imagorpath.Signer
	GetSigner              func(*http.Request) imagorpath.Signer
	GetResultKey           func(*http.Request, imagorpath.Params) string
	StoragePathStyle       imagorpath.StorageHasher
	ResultStoragePathStyle imagorpath.ResultStorageHasher
	BasePathRedirect       string
	Loaders                []Loader
	Storages               []Storage
	ResultStorages         []Storage
	Processors             []Processor
	RequestTimeout         time.Duration
	LoadTimeout            time.Duration
	SaveTimeout            time.Duration
	ProcessTimeout         time.Duration
	CacheHeaderTTL         time.Duration
	CacheHeaderSWR         time.Duration
	ProcessConcurrency     int64
	ProcessQueueSize       int64
	AutoWebP               bool
	AutoAVIF               bool
	AutoJPEG               bool
	ModifiedTimeCheck      bool
	DisableErrorBody       bool
	DisableParamsEndpoint  bool
	EnablePostRequests     bool
	ResponseRawOnError     bool
	BaseParams             string
	Logger                 *zap.Logger
	Debug                  bool
	// contains filtered or unexported fields
}

Imagor main application

func New

func New(options ...Option) *Imagor

New create new Imagor

func (*Imagor) Do

func (app *Imagor) Do(r *http.Request, p imagorpath.Params) (blob *Blob, err error)

Do executes imagor operations

func (*Imagor) Serve added in v1.3.0

func (app *Imagor) Serve(ctx context.Context, p imagorpath.Params) (*Blob, error)

Serve serves imagor by context and params

func (*Imagor) ServeBlob added in v1.3.1

func (app *Imagor) ServeBlob(
	ctx context.Context, blob *Blob, p imagorpath.Params,
) (*Blob, error)

ServeBlob serves imagor Blob with context and params, skipping loader and storages

func (*Imagor) ServeHTTP

func (app *Imagor) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler for imagor operations

func (*Imagor) Shutdown

func (app *Imagor) Shutdown(ctx context.Context) (err error)

Shutdown Imagor shutdown lifecycle

func (*Imagor) Startup

func (app *Imagor) Startup(ctx context.Context) (err error)

Startup Imagor startup lifecycle

type LoadFunc

type LoadFunc func(string) (*Blob, error)

LoadFunc function handler for Processor to call loader

type Loader

type Loader interface {
	Get(r *http.Request, key string) (*Blob, error)
}

Loader image loader interface

type Option

type Option func(app *Imagor)

Option imagor option

func WithAutoAVIF added in v0.8.19

func WithAutoAVIF(enable bool) Option

WithAutoAVIF experimental with auto AVIF option based on browser Accept header

func WithAutoJPEG added in v1.5.16

func WithAutoJPEG(enable bool) Option

WithAutoJPEG with auto JPEG option when JPEG or no specific format is requested

func WithAutoWebP added in v0.8.16

func WithAutoWebP(enable bool) Option

WithAutoWebP with auto WebP option based on browser Accept header

func WithBaseParams added in v0.9.0

func WithBaseParams(params string) Option

WithBaseParams with base params string option

func WithBasePathRedirect added in v0.8.16

func WithBasePathRedirect(url string) Option

WithBasePathRedirect with base path redirect option

func WithCacheHeaderNoCache added in v0.8.26

func WithCacheHeaderNoCache(nocache bool) Option

WithCacheHeaderNoCache with browser cache header no-cache option

func WithCacheHeaderSWR added in v0.8.26

func WithCacheHeaderSWR(swr time.Duration) Option

WithCacheHeaderSWR with browser cache header swr option

func WithCacheHeaderTTL added in v0.1.5

func WithCacheHeaderTTL(ttl time.Duration) Option

WithCacheHeaderTTL with browser cache header ttl option

func WithDebug

func WithDebug(debug bool) Option

WithDebug with debug option

func WithDetector added in v1.8.0

func WithDetector(d Detector) Option

WithDetector wires d into every DetectorAdder processor in the app. Passing nil is a no-op, allowing callers to unconditionally call WithDetector and skip wiring when the feature is disabled.

func WithDetectors added in v1.8.0

func WithDetectors(ds ...Detector) Option

WithDetectors wires multiple detectors into every DetectorAdder processor in the app. Like WithDetector, nil entries are skipped.

func WithDisableErrorBody added in v0.9.0

func WithDisableErrorBody(disabled bool) Option

WithDisableErrorBody with disable error body option, resulting empty response on error

func WithDisableParamsEndpoint added in v0.9.0

func WithDisableParamsEndpoint(disabled bool) Option

WithDisableParamsEndpoint with disable imagor /params endpoint

func WithEnablePostRequests added in v1.6.0

func WithEnablePostRequests(enable bool) Option

WithEnablePostRequests with enable POST requests option

func WithGetResultKey added in v1.8.5

func WithGetResultKey(fn func(*http.Request, imagorpath.Params) string) Option

func WithGetSigner added in v1.8.5

func WithGetSigner(fn func(*http.Request) imagorpath.Signer) Option

func WithLoadTimeout added in v0.1.5

func WithLoadTimeout(timeout time.Duration) Option

WithLoadTimeout with load timeout option for loader and storage

func WithLoaders

func WithLoaders(loaders ...Loader) Option

WithLoaders with loaders option

func WithLogger

func WithLogger(logger *zap.Logger) Option

WithLogger with logger option

func WithModifiedTimeCheck added in v0.8.23

func WithModifiedTimeCheck(enabled bool) Option

WithModifiedTimeCheck with option for modified time check of storage against result storage

func WithOptions added in v1.2.3

func WithOptions(options ...Option) Option

WithOptions with nested options

func WithProcessConcurrency added in v0.8.7

func WithProcessConcurrency(concurrency int64) Option

WithProcessConcurrency maximum number of processor call to be executed simultaneously.

func WithProcessQueueSize added in v0.9.13

func WithProcessQueueSize(size int64) Option

WithProcessQueueSize maximum number of processor call that can be put to a queue

func WithProcessTimeout added in v0.5.4

func WithProcessTimeout(timeout time.Duration) Option

WithProcessTimeout with process timeout option for processor

func WithProcessors

func WithProcessors(processors ...Processor) Option

WithProcessors with processor option

func WithRequestTimeout

func WithRequestTimeout(timeout time.Duration) Option

WithRequestTimeout with request timeout option

func WithResponseRawOnError added in v1.6.16

func WithResponseRawOnError(enabled bool) Option

WithResponseRawOnError with response raw on error option

func WithResultStoragePathStyle added in v1.1.0

func WithResultStoragePathStyle(hasher imagorpath.ResultStorageHasher) Option

WithResultStoragePathStyle with result storage path style hasher option

func WithResultStorages added in v0.5.5

func WithResultStorages(savers ...Storage) Option

WithResultStorages with result storages option

func WithSaveTimeout

func WithSaveTimeout(timeout time.Duration) Option

WithSaveTimeout with save timeout option for storage

func WithSigner added in v0.8.23

func WithSigner(signer imagorpath.Signer) Option

WithSigner with URL signature signer option

func WithStoragePathStyle added in v1.1.0

func WithStoragePathStyle(hasher imagorpath.StorageHasher) Option

WithStoragePathStyle with storage path style hasher option

func WithStorages

func WithStorages(savers ...Storage) Option

WithStorages with storages option

func WithUnsafe

func WithUnsafe(unsafe bool) Option

WithUnsafe with unsafe option

type Processor

type Processor interface {
	// Startup processor startup lifecycle,
	// called only once for the application lifetime
	Startup(ctx context.Context) error

	// Process Blob with given params and loader function
	Process(ctx context.Context, blob *Blob, params imagorpath.Params, load LoadFunc) (*Blob, error)

	// Shutdown processor shutdown lifecycle,
	// called only once for the application lifetime
	Shutdown(ctx context.Context) error
}

Processor process image buffer

type Stat added in v0.8.23

type Stat struct {
	ModifiedTime time.Time
	ETag         string
	Size         int64
}

Stat Blob stat attributes

type Stater added in v1.5.16

type Stater interface {
	Stat(ctx context.Context, key string) (*Stat, error)
}

Stater optional interface for loaders that support stat operations

type Storage

type Storage interface {
	// Get data Blob by key
	Get(r *http.Request, key string) (*Blob, error)

	// Stat get Blob Stat by key
	Stat(ctx context.Context, key string) (*Stat, error)

	// Put data Blob by key
	Put(ctx context.Context, key string, blob *Blob) error

	// Delete delete data Blob by key
	Delete(ctx context.Context, key string) error
}

Storage image storage interface

type TemplateData added in v1.6.0

type TemplateData struct {
	Version string
	Path    string
	Params  interface{}
}

TemplateData holds data for template rendering

Directories

Path Synopsis
cmd
imagor command
examples
from_buffer command
from_file command
from_go_image command
server command
loader
metrics
processor
storage

Jump to

Keyboard shortcuts

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