imagorpath

package
v1.10.4 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: Apache-2.0 Imports: 11 Imported by: 8

README

imagorpath

Parse and generate imagor endpoint using Go struct

import "github.com/cshum/imagor/imagorpath"

...

func Test(t *testing.T) {
	params := imagorpath.Params{
		Image:    "raw.githubusercontent.com/cshum/imagor/master/testdata/gopher.png",
		FitIn:    true,
		Width:    500,
		Height:   400,
		PaddingTop: 20,
		PaddingBottom: 20,
		Filters: imagorpath.Filters{
			{
				Name: "fill",
				Args: "white",
			},
		},
	}

	// generate signed imagor endpoint from Params struct with secret
	path := imagorpath.Generate(params, imagorpath.NewDefaultSigner("mysecret"))

	assert.Equal(t, path, "OyGJyvfYJw8xNkYDmXU-4NPA2U0=/fit-in/500x400/0x20/filters:fill(white)/raw.githubusercontent.com/cshum/imagor/master/testdata/gopher.png")

	assert.Equal(t,
		// parse Params struct from signed imagor endpoint
		imagorpath.Parse(path),

		// Params include endpoint attributes with path and signed hash
		imagorpath.Params{
			Path:     "fit-in/500x400/0x20/filters:fill(white)/raw.githubusercontent.com/cshum/imagor/master/testdata/gopher.png",
			Hash:     "OyGJyvfYJw8xNkYDmXU-4NPA2U0=",
			Image:    "raw.githubusercontent.com/cshum/imagor/master/testdata/gopher.png",
			FitIn:    true,
			Width:    500,
			Height:   400,
			PaddingTop: 20,
			PaddingBottom: 20,
			Filters: imagorpath.Filters{
				{
					Name: "fill",
					Args: "white",
				},
			},
		},
	)
}

Documentation

Index

Constants

View Source
const (
	// TrimByTopLeft trim by top-left keyword
	TrimByTopLeft = "top-left"
	// TrimByBottomRight trim by bottom-right keyword
	TrimByBottomRight = "bottom-right"
	// HAlignLeft horizontal align left keyword
	HAlignLeft = "left"
	// HAlignRight horizontal align right keyword
	HAlignRight = "right"
	// VAlignTop vertical align top keyword
	VAlignTop = "top"
	// VAlignBottom vertical align bottom keyword
	VAlignBottom = "bottom"
)

Variables

View Source
var DigestResultStorageHasher = ResultStorageHasherFunc(func(p Params) string {
	if p.Path == "" {
		p.Path = GeneratePath(p)
	}
	return hexDigestPath(p.Path)
})

DigestResultStorageHasher ResultStorageHasher using SHA digest

View Source
var DigestStorageHasher = StorageHasherFunc(hexDigestPath)

DigestStorageHasher StorageHasher using SHA digest

View Source
var SizeSuffixResultStorageHasher = ResultStorageHasherFunc(func(p Params) string {
	if p.Path == "" {
		p.Path = GeneratePath(p)
	}
	var digest = sha1.Sum([]byte(p.Path))
	var hash = "." + hex.EncodeToString(digest[:])[:20]
	if p.Width != 0 || p.Height != 0 {
		hash += "_" + strconv.Itoa(p.Width) + "x" + strconv.Itoa(p.Height)
	}
	var dotIdx = strings.LastIndex(p.Image, ".")
	var slashIdx = strings.LastIndex(p.Image, "/")
	if dotIdx > -1 && slashIdx < dotIdx {
		ext := p.Image[dotIdx:]
		if p.Meta {
			ext = ".json"
		} else {
			for _, filter := range p.Filters {
				if filter.Name == "format" {
					ext = "." + filter.Args
				}
			}
		}
		return p.Image[:dotIdx] + hash + ext
	}
	return p.Image + hash
})

SizeSuffixResultStorageHasher ResultStorageHasher using storage path with digest and size suffix

View Source
var SuffixResultStorageHasher = ResultStorageHasherFunc(func(p Params) string {
	if p.Path == "" {
		p.Path = GeneratePath(p)
	}
	var digest = sha1.Sum([]byte(p.Path))
	var hash = "." + hex.EncodeToString(digest[:])[:20]
	var dotIdx = strings.LastIndex(p.Image, ".")
	var slashIdx = strings.LastIndex(p.Image, "/")
	if dotIdx > -1 && slashIdx < dotIdx {
		ext := p.Image[dotIdx:]
		if p.Meta {
			ext = ".json"
		} else {
			for _, filter := range p.Filters {
				if filter.Name == "format" {
					ext = "." + filter.Args
				}
			}
		}
		return p.Image[:dotIdx] + hash + ext
	}
	return p.Image + hash
})

SuffixResultStorageHasher ResultStorageHasher using storage path with digest suffix

Functions

func Generate

func Generate(p Params, signer Signer) string

Generate imagor endpoint with signature by Params struct with signer

func GeneratePath added in v0.8.16

func GeneratePath(p Params) string

GeneratePath generate imagor path by Params struct

func GenerateUnsafe

func GenerateUnsafe(p Params) string

GenerateUnsafe generate unsafe imagor endpoint by Params struct

func HasCacheBypass added in v1.7.3

func HasCacheBypass(p Params) bool

HasCacheBypass reports whether the params require bypassing the image cache. The cache stores a downscaled copy keyed by image path only. Requests that depend on original-space coordinates or per-request decode parameters must bypass the cache to avoid incorrect results:

  • crop coordinates (absolute or percentage) are in original image space
  • focal() filter uses original image coordinates for smart crop
  • page(n>1) selects a specific page/frame; cache stores page 1 only
  • dpi(n) affects SVG/PDF render resolution; cache stores at default DPI

func HasCrop added in v1.7.3

func HasCrop(p Params) bool

HasCrop reports whether the params specify a crop region. Any non-zero crop coordinate (left, top, right, or bottom) counts as a crop.

func HasFilter added in v1.7.3

func HasFilter(p Params, name string) bool

HasFilter reports whether the params include at least one filter with the given name.

func HasTransformations added in v1.9.7

func HasTransformations(p Params, ignoreFilters ...string) bool

HasTransformations reports whether the params ask imagor to do anything to the image: a resize, fit, stretch, alignment, padding, flip, crop, trim, smart crop, or any filter that is not in ignoreFilters. ignoreFilters lets a caller skip filters it has already accounted for - a format the server chose, or the application's own - so it need not guess which filters a client named.

func Normalize added in v0.5.15

func Normalize(image string, safeChars SafeChars) string

Normalize imagor path to be file path friendly, optional escapeByte func for custom SafeChars

func ResolveFullDim added in v1.9.10

func ResolveFullDim(token string, parentDim int) string

ResolveFullDim resolves a single dimension token against a parent pixel size. Tokens of the form f or f-NNN (with optional leading - for flip) resolve to parentDim - NNN. Any other token is returned unchanged.

func ResolveFullDimensions added in v1.9.10

func ResolveFullDimensions(imagorPath string, parentW, parentH int) string

ResolveFullDimensions rewrites f‑tokens in the WxH dimension segment of an imagor path, substituting the parent image's pixel dimensions before the path is parsed. Only the first WxH dimension segment is considered — it always appears before filters: in a valid imagor path. The function stops at the first dimSegmentRegex match or at a filters: prefix, ensuring nested layer paths inside filter arguments are not accidentally resolved at this level.

This is how a nested path inherits the parent's dimensions: it lives here rather than in a processor so that every caller that resolves a nested path — the image() filter and a path: source alike — resolves f-tokens the same way.

func SplitArgs added in v1.6.10

func SplitArgs(args string) []string

SplitArgs splits filter arguments by comma, respecting parentheses nesting. This allows nested filter paths with commas to work correctly. Example: "path(a,b),x,y" -> ["path(a,b)", "x", "y"]

Types

type Filter

type Filter struct {
	Name string `json:"name,omitempty"`
	Args string `json:"args,omitempty"`
}

Filter imagor endpoint filter

type Filters

type Filters []Filter

Filters a slice of Filter

type Params

type Params struct {
	Params        bool    `json:"-"`
	Path          string  `json:"path,omitempty"`
	Image         string  `json:"image,omitempty"`
	Base64Image   bool    `json:"base64_image,omitempty"`
	Unsafe        bool    `json:"unsafe,omitempty"`
	Hash          string  `json:"hash,omitempty"`
	Meta          bool    `json:"meta,omitempty"`
	Trim          bool    `json:"trim,omitempty"`
	TrimBy        string  `json:"trim_by,omitempty"`
	TrimTolerance int     `json:"trim_tolerance,omitempty"`
	CropLeft      float64 `json:"crop_left,omitempty"`
	CropTop       float64 `json:"crop_top,omitempty"`
	CropRight     float64 `json:"crop_right,omitempty"`
	CropBottom    float64 `json:"crop_bottom,omitempty"`
	FitIn         bool    `json:"fit_in,omitempty"`
	AdaptiveFitIn bool    `json:"adaptive_fit_in,omitempty"`
	FullFitIn     bool    `json:"full_fit_in,omitempty"`
	Stretch       bool    `json:"stretch,omitempty"`
	Width         int     `json:"width,omitempty"`
	Height        int     `json:"height,omitempty"`
	PaddingLeft   int     `json:"padding_left,omitempty"`
	PaddingTop    int     `json:"padding_top,omitempty"`
	PaddingRight  int     `json:"padding_right,omitempty"`
	PaddingBottom int     `json:"padding_bottom,omitempty"`
	HFlip         bool    `json:"h_flip,omitempty"`
	VFlip         bool    `json:"v_flip,omitempty"`
	HAlign        string  `json:"h_align,omitempty"`
	VAlign        string  `json:"v_align,omitempty"`
	Smart         bool    `json:"smart,omitempty"`
	Filters       Filters `json:"filters,omitempty"`
}

Params image endpoint parameters

func Apply added in v0.9.0

func Apply(p Params, path string) Params

Apply Params struct from imagor endpoint URI on top of existing Params

func Parse

func Parse(path string) Params

Parse Params struct from imagor endpoint URI

type ResultStorageHasher added in v1.1.0

type ResultStorageHasher interface {
	HashResult(p Params) string
}

ResultStorageHasher define key for result storage

type ResultStorageHasherFunc added in v1.1.0

type ResultStorageHasherFunc func(p Params) string

ResultStorageHasherFunc ResultStorageHasher handler func

func (ResultStorageHasherFunc) HashResult added in v1.1.0

func (h ResultStorageHasherFunc) HashResult(p Params) string

HashResult implements ResultStorageHasher interface

type SafeChars added in v0.8.23

type SafeChars interface {
	// ShouldEscape indicates if char byte should be escaped
	ShouldEscape(c byte) bool
}

SafeChars safe chars for storage paths

func NewNoopSafeChars added in v1.4.9

func NewNoopSafeChars() SafeChars

NewNoopSafeChars create no-op SafeChars

func NewSafeChars added in v0.8.23

func NewSafeChars(safechars string) SafeChars

NewSafeChars create SafeChars from predefined set of string, or "--" for no-op

type Signer added in v0.8.23

type Signer interface {
	Sign(path string) string
}

Signer imagor URL signature signer

func NewDefaultSigner added in v0.8.23

func NewDefaultSigner(secret string) Signer

NewDefaultSigner default signer using SHA1 with secret

func NewHMACSigner added in v0.8.23

func NewHMACSigner(alg func() hash.Hash, truncate int, secret string) Signer

NewHMACSigner custom HMAC alg signer with secret and string length based truncate

type StorageHasher added in v1.1.0

type StorageHasher interface {
	Hash(image string) string
}

StorageHasher define image key for storage

type StorageHasherFunc added in v1.1.0

type StorageHasherFunc func(image string) string

StorageHasherFunc StorageHasher handler func

func (StorageHasherFunc) Hash added in v1.1.0

func (h StorageHasherFunc) Hash(image string) string

Hash implements StorageHasher interface

Jump to

Keyboard shortcuts

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