imageproxy: willnorris.com/go/imageproxy Index | Files | Directories

package imageproxy

import "willnorris.com/go/imageproxy"

Package imageproxy provides an image proxy server. For typical use of creating and using a Proxy, see cmd/imageproxy/main.go.

Index

Package Files

cache.go data.go imageproxy.go transform.go

Variables

var NopCache = new(nopCache)

NopCache provides a no-op cache implementation that doesn't actually cache anything.

func Transform Uses

func Transform(img []byte, opt Options) ([]byte, error)

Transform the provided image. img should contain the raw bytes of an encoded image in one of the supported formats (gif, jpeg, or png). The bytes of a similarly encoded image is returned.

type Cache Uses

type Cache interface {
    // Get retrieves the cached data for the provided key.
    Get(key string) (data []byte, ok bool)

    // Set caches the provided data.
    Set(key string, data []byte)

    // Delete deletes the cached data at the specified key.
    Delete(key string)
}

The Cache interface defines a cache for storing arbitrary data. The interface is designed to align with httpcache.Cache.

type Options Uses

type Options struct {
    // See ParseOptions for interpretation of Width and Height values
    Width  float64
    Height float64

    // If true, resize the image to fit in the specified dimensions.  Image
    // will not be cropped, and aspect ratio will be maintained.
    Fit bool

    // Rotate image the specified degrees counter-clockwise.  Valid values
    // are 90, 180, 270.
    Rotate int

    FlipVertical   bool
    FlipHorizontal bool

    // Quality of output image
    Quality int

    // HMAC Signature for signed requests.
    Signature string

    // Allow image to scale beyond its original dimensions.  This value
    // will always be overwritten by the value of Proxy.ScaleUp.
    ScaleUp bool

    // Desired image format. Valid values are "jpeg", "png", "tiff".
    Format string

    // Crop rectangle params
    CropX      float64
    CropY      float64
    CropWidth  float64
    CropHeight float64

    // Automatically find good crop points based on image content.
    SmartCrop bool
}

Options specifies transformations to be performed on the requested image.

func ParseOptions Uses

func ParseOptions(str string) Options

ParseOptions parses str as a list of comma separated transformation options. The options can be specified in in order, with duplicate options overwriting previous values.

Rectangle Crop

There are four options controlling rectangle crop:

cx{x}      - X coordinate of top left rectangle corner (default: 0)
cy{y}      - Y coordinate of top left rectangle corner (default: 0)
cw{width}  - rectangle width (default: image width)
ch{height} - rectangle height (default: image height)

For all options, integer values are interpreted as exact pixel values and floats between 0 and 1 are interpreted as percentages of the original image size. Negative values for cx and cy are measured from the right and bottom edges of the image, respectively.

If the crop width or height exceed the width or height of the image, the crop width or height will be adjusted, preserving the specified cx and cy values. Rectangular crop is applied before any other transformations.

Smart Crop

The "sc" option will perform a content-aware smart crop to fit the requested image width and height dimensions (see Size and Cropping below). The smart crop option will override any requested rectangular crop.

Size and Cropping

The size option takes the general form "{width}x{height}", where width and height are numbers. Integer values greater than 1 are interpreted as exact pixel values. Floats between 0 and 1 are interpreted as percentages of the original image size. If either value is omitted or set to 0, it will be automatically set to preserve the aspect ratio based on the other dimension. If a single number is provided (with no "x" separator), it will be used for both height and width.

Depending on the size options specified, an image may be cropped to fit the requested size. In all cases, the original aspect ratio of the image will be preserved; imageproxy will never stretch the original image.

When no explicit crop mode is specified, the following rules are followed:

- If both width and height values are specified, the image will be scaled to fill the space, cropping if necessary to fit the exact dimension.

- If only one of the width or height values is specified, the image will be resized to fit the specified dimension, scaling the other dimension as needed to maintain the aspect ratio.

If the "fit" option is specified together with a width and height value, the image will be resized to fit within a containing box of the specified size. As always, the original aspect ratio will be preserved. Specifying the "fit" option with only one of either width or height does the same thing as if "fit" had not been specified.

Rotation and Flips

The "r{degrees}" option will rotate the image the specified number of degrees, counter-clockwise. Valid degrees values are 90, 180, and 270.

The "fv" option will flip the image vertically. The "fh" option will flip the image horizontally. Images are flipped after being rotated.

Quality

The "q{qualityPercentage}" option can be used to specify the quality of the output file (JPEG only). If not specified, the default value of "95" is used.

Format

The "jpeg", "png", and "tiff" options can be used to specify the desired image format of the proxied image.

Signature

The "s{signature}" option specifies an optional base64 encoded HMAC used to sign the remote URL in the request. The HMAC key used to verify signatures is provided to the imageproxy server on startup.

See https://github.com/willnorris/imageproxy/blob/master/docs/url-signing.md for examples of generating signatures.

Examples

0x0         - no resizing
200x        - 200 pixels wide, proportional height
x0.15       - 15% original height, proportional width
100x150     - 100 by 150 pixels, cropping as needed
100         - 100 pixels square, cropping as needed
150,fit     - scale to fit 150 pixels square, no cropping
100,r90     - 100 pixels square, rotated 90 degrees
100,fv,fh   - 100 pixels square, flipped horizontal and vertical
200x,q60    - 200 pixels wide, proportional height, 60% quality
200x,png    - 200 pixels wide, converted to PNG format
cw100,ch100 - crop image to 100px square, starting at (0,0)
cx10,cy20,cw100,ch200 - crop image starting at (10,20) is 100px wide and 200px tall

func (Options) String Uses

func (o Options) String() string

type Proxy Uses

type Proxy struct {
    Client *http.Client // client used to fetch remote URLs
    Cache  Cache        // cache used to cache responses

    // AllowHosts specifies a list of remote hosts that images can be
    // proxied from.  An empty list means all hosts are allowed.
    AllowHosts []string

    // DenyHosts specifies a list of remote hosts that images cannot be
    // proxied from.
    DenyHosts []string

    // Referrers, when given, requires that requests to the image
    // proxy come from a referring host. An empty list means all
    // hosts are allowed.
    Referrers []string

    // DefaultBaseURL is the URL that relative remote URLs are resolved in
    // reference to.  If nil, all remote URLs specified in requests must be
    // absolute.
    DefaultBaseURL *url.URL

    // The Logger used by the image proxy
    Logger *log.Logger

    // SignatureKey is the HMAC key used to verify signed requests.
    SignatureKey []byte

    // Allow images to scale beyond their original dimensions.
    ScaleUp bool

    // Timeout specifies a time limit for requests served by this Proxy.
    // If a call runs for longer than its time limit, a 504 Gateway Timeout
    // response is returned.  A Timeout of zero means no timeout.
    Timeout time.Duration

    // If true, log additional debug messages
    Verbose bool

    // ContentTypes specifies a list of content types to allow. An empty
    // list means all content types are allowed.
    ContentTypes []string

    // The User-Agent used by imageproxy when requesting origin image
    UserAgent string
}

Proxy serves image requests.

func NewProxy Uses

func NewProxy(transport http.RoundTripper, cache Cache) *Proxy

NewProxy constructs a new proxy. The provided http RoundTripper will be used to fetch remote URLs. If nil is provided, http.DefaultTransport will be used.

func (*Proxy) ServeHTTP Uses

func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP handles incoming requests.

type Request Uses

type Request struct {
    URL      *url.URL      // URL of the image to proxy
    Options  Options       // Image transformation to perform
    Original *http.Request // The original HTTP request
}

Request is an imageproxy request which includes a remote URL of an image to proxy, and an optional set of transformations to perform.

func NewRequest Uses

func NewRequest(r *http.Request, baseURL *url.URL) (*Request, error)

NewRequest parses an http.Request into an imageproxy Request. Options and the remote image URL are specified in the request path, formatted as: /{options}/{remote_url}. Options may be omitted, so a request path may simply contain /{remote_url}. The remote URL must be an absolute "http" or "https" URL, should not be URL encoded, and may contain a query string.

Assuming an imageproxy server running on localhost, the following are all valid imageproxy requests:

http://localhost/100x200/http://example.com/image.jpg
http://localhost/100x200,r90/http://example.com/image.jpg?foo=bar
http://localhost//http://example.com/image.jpg
http://localhost/http://example.com/image.jpg

func (Request) String Uses

func (r Request) String() string

String returns the request URL as a string, with r.Options encoded in the URL fragment.

type TransformingTransport Uses

type TransformingTransport struct {
    // Transport is the underlying http.RoundTripper used to satisfy
    // non-transform requests (those that do not include a URL fragment).
    Transport http.RoundTripper

    // CachingClient is used to fetch images to be resized.  This client is
    // used rather than Transport directly in order to ensure that
    // responses are properly cached.
    CachingClient *http.Client
    // contains filtered or unexported fields
}

TransformingTransport is an implementation of http.RoundTripper that optionally transforms images using the options specified in the request URL fragment.

func (*TransformingTransport) RoundTrip Uses

func (t *TransformingTransport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements the http.RoundTripper interface.

type URLError Uses

type URLError struct {
    Message string
    URL     *url.URL
}

URLError reports a malformed URL error.

func (URLError) Error Uses

func (e URLError) Error() string

Directories

PathSynopsis
cmd/imageproxyimageproxy starts an HTTP server that proxies requests for remote images.
cmd/imageproxy-signThe imageproxy-sign tool creates signature values for a provided URL and signing key.
internal/gcscachePackage gcscache provides an httpcache.Cache implementation that stores cached values on Google Cloud Storage.
internal/s3cachePackage s3cache provides an httpcache.Cache implementation that stores cached values on Amazon S3.
third_party/httpPackage http provides helpers for HTTP servers.

Package imageproxy imports 33 packages (graph) and is imported by 6 packages. Updated 2019-05-14. Refresh now. Tools for package owners.