### Install imageproxy Source: https://github.com/willnorris/imageproxy/blob/main/README.md Install the imageproxy command-line tool using Go modules. Ensure your GOPATH/bin is in your PATH. ```sh go install willnorris.com/go/imageproxy/cmd/imageproxy@latest ``` -------------------------------- ### Full Production Configuration for imageproxy Source: https://context7.com/willnorris/imageproxy/llms.txt A comprehensive example of starting imageproxy with various production-ready settings including address, tiered caching, host restrictions, referrers, signature key, timeout, content types, and verbose logging. ```bash imageproxy \ -addr 0.0.0.0:8080 \ -cache memory:100 \ -cache /var/cache/imageproxy \ -allowHosts "example.com,*.cdn.example.com" \ -denyHosts "internal.example.com,192.168.0.0/16" \ -referrers "example.com,*.example.com" \ -signatureKey "your-secret-key" \ -timeout 30s \ -contentTypes "image/*" \ -verbose ``` -------------------------------- ### Imageproxy URL Examples Source: https://github.com/willnorris/imageproxy/blob/main/README.md Examples demonstrating image transformations via URL parameters. Use 'sc' for smart crop. ```html 200x400,sc ``` ```html 200x400 ``` ```html 200,r270 ``` -------------------------------- ### Build and Install Imageproxy Binary Source: https://github.com/willnorris/imageproxy/blob/main/README.md Standard Go application build and installation process. Copy the resulting binary to a system path and the service file to the systemd directory. ```sh go build willnorris.com/go/imageproxy/cmd/imageproxy copy resulting binary to /usr/local/bin copy etc/imageproxy.service to /lib/systemd/system and enable using systemctl. ``` -------------------------------- ### Docker Compose Example for Imageproxy Source: https://context7.com/willnorris/imageproxy/llms.txt Example Docker Compose configuration for imageproxy, demonstrating environment variable settings for cache, allowed hosts, and timeouts. ```yaml # Docker Compose example # docker-compose.yml: # version: '3' # services: # imageproxy: # image: ghcr.io/willnorris/imageproxy # ports: # - "8080:8080" # environment: # - IMAGEPROXY_CACHE=memory:500 # - IMAGEPROXY_ALLOWHOSTS=*.example.com # - IMAGEPROXY_TIMEOUT=30s # command: ["-addr", "0.0.0.0:8080"] ``` -------------------------------- ### Start imageproxy with Custom Address and Disk Caching Source: https://context7.com/willnorris/imageproxy/llms.txt Starts the imageproxy server on port 3000 and configures disk caching in the /tmp/imageproxy directory. ```bash imageproxy -addr :3000 -cache /tmp/imageproxy ``` -------------------------------- ### Start imageproxy with In-Memory Cache Configuration Source: https://context7.com/willnorris/imageproxy/llms.txt Starts the imageproxy server using an in-memory cache with a maximum size of 200MB and a maximum age of 4 hours. ```bash imageproxy -cache memory:200:4h ``` -------------------------------- ### Sign URL with JavaScript Source: https://github.com/willnorris/imageproxy/blob/main/docs/url-signing.md This JavaScript example signs a URL using Node.js 'crypto' module and 'urlsafe-base64' package. Ensure you have installed 'urlsafe-base64'. ```javascript const crypto = require("crypto"); const URLSafeBase64 = require("urlsafe-base64"); let key = process.argv[2]; let url = process.argv[3]; console.log( URLSafeBase64.encode(crypto.createHmac("sha256", key).update(url).digest()), ); ``` ```shell $ node sign.js "secretkey" "https://octodex.github.com/images/codercat.jpg" ``` -------------------------------- ### Run imageproxy Source: https://github.com/willnorris/imageproxy/blob/main/README.md Start the imageproxy server. By default, it runs on port 8080 without caching and allows any remote URL. ```sh imageproxy ``` -------------------------------- ### Start imageproxy with Redis Caching Source: https://context7.com/willnorris/imageproxy/llms.txt Configures imageproxy to use Redis for caching. The Redis password can be provided via an environment variable. ```bash REDIS_PASSWORD=secret imageproxy -cache "redis://localhost:6379/" ``` -------------------------------- ### Start imageproxy with Tiered Caching (Memory and Disk) Source: https://context7.com/willnorris/imageproxy/llms.txt Configures imageproxy with multiple cache layers, using an in-memory cache of 100MB followed by disk caching at /var/cache/imageproxy. ```bash imageproxy -cache memory:100 -cache /var/cache/imageproxy ``` -------------------------------- ### Start imageproxy with Azure Storage Caching Source: https://context7.com/willnorris/imageproxy/llms.txt Configures imageproxy to use Azure Storage for caching. Account name and access key should be provided via environment variables. ```bash AZURESTORAGE_ACCOUNT_NAME=myaccount AZURESTORAGE_ACCESS_KEY=key imageproxy -cache "azure://container/" ``` -------------------------------- ### Start imageproxy with Google Cloud Storage Caching Source: https://context7.com/willnorris/imageproxy/llms.txt Configures imageproxy to use Google Cloud Storage for caching, specifying the bucket name and an optional prefix. ```bash imageproxy -cache "gcs://my-bucket/prefix" ``` -------------------------------- ### Basic Docker Run for Imageproxy Source: https://context7.com/willnorris/imageproxy/llms.txt Run the official imageproxy Docker image, exposing port 8080. This is a basic setup for testing or simple deployments. ```bash # Basic Docker run docker run -p 8080:8080 ghcr.io/willnorris/imageproxy -addr 0.0.0.0:8080 ``` -------------------------------- ### Start imageproxy with S3 Caching Source: https://context7.com/willnorris/imageproxy/llms.txt Configures imageproxy to use Amazon S3 for caching, specifying the region, bucket name, and an optional cache prefix. ```bash imageproxy -cache "s3://us-east-1/my-bucket/cache-prefix" ``` -------------------------------- ### Test imageproxy with a remote URL Source: https://github.com/willnorris/imageproxy/blob/main/README.md Access a remote image through the running imageproxy server. This example requests a 500px square version of an Octocat image. ```html http://localhost:8080/500/https://octodex.github.com/images/codercat.jpg ``` -------------------------------- ### Implement Custom Cache Interface in Go Source: https://context7.com/willnorris/imageproxy/llms.txt Implement the `imageproxy.Cache` interface to create custom caching backends. This example shows a simple in-memory cache using a map. ```go package main import ( "sync" "willnorris.com/go/imageproxy" ) // SimpleCache implements imageproxy.Cache with a simple map type SimpleCache struct { mu sync.RWMutex store map[string][]byte } func NewSimpleCache() *SimpleCache { return &SimpleCache{store: make(map[string][]byte)} } func (c *SimpleCache) Get(key string) ([]byte, bool) { c.mu.RLock() defer c.mu.RUnlock() data, ok := c.store[key] return data, ok } func (c *SimpleCache) Set(key string, data []byte) { c.mu.Lock() defer c.mu.Unlock() c.store[key] = data } func (c *SimpleCache) Delete(key string) { c.mu.Lock() defer c.mu.Unlock() delete(c.store, key) } func main() { cache := NewSimpleCache() p := imageproxy.NewProxy(nil, cache) // Use proxy... _ = p } ``` -------------------------------- ### S3 Cache Configuration with Minio Source: https://github.com/willnorris/imageproxy/blob/main/README.md Example of configuring imageproxy to cache images on an S3-compatible service like Minio, specifying a custom endpoint and disabling SSL. ```url s3://fake-region/bucket/folder?endpoint=minio:9000&disableSSL=1&s3ForcePathStyle=1 ``` -------------------------------- ### Generate Signed Request in Go Source: https://github.com/willnorris/imageproxy/wiki/URL-signing Use Go's crypto/hmac and encoding/base64 packages to generate a signed URL. This example takes the secret key and the target URL as command-line arguments. ```go package main import ( "os" "fmt" "crypto/hmac" "crypto/sha256" "encoding/base64" ) func main() { mac := hmac.New(sha256.New, []byte(os.Args[1])) mac.Write([]byte(os.Args[2])) want := mac.Sum(nil) fmt.Println("result: ",base64.URLEncoding.EncodeToString(want)) } ``` ```shell $ go run main.go "test" "https://www.google.fr/images/srpr/logo11w.png" result: RYifAJRfbhsitJeOrDNxWURCCkPsVR4ihCPXNv-ePbA= ``` -------------------------------- ### S3 Cache Configuration for Digital Ocean Spaces Source: https://github.com/willnorris/imageproxy/blob/main/README.md Example of configuring imageproxy to cache images on Digital Ocean Spaces, providing a dummy region and the correct endpoint. ```url s3://fake-region/bucket/folder?endpoint=sfo2.digitaloceanspaces.com ``` -------------------------------- ### Proxy Requests to Imageproxy with Caddy Source: https://github.com/willnorris/imageproxy/blob/main/README.md Configure Caddy to proxy requests to an imageproxy instance. This example sets up a path-based routing rule and replaces the API path before forwarding. ```Caddyfile @imageproxy path /api/imageproxy/* handle @imageproxy { uri replace /api/imageproxy/ / reverse_proxy http://localhost:4593 } ``` -------------------------------- ### Proxy Requests to Imageproxy with nginx Source: https://github.com/willnorris/imageproxy/blob/main/README.md Configure nginx to proxy requests to an imageproxy instance using the 'proxy_pass' directive. This example sets up routing for the '/api/imageproxy/' path. ```nginx location /api/imageproxy/ { proxy_pass http://localhost:4593/; } ``` -------------------------------- ### Go signature generation function Source: https://context7.com/willnorris/imageproxy/llms.txt Example Go function to generate HMAC-SHA256 signatures for URLs. This function takes a secret key and a URL, and returns the base64-encoded signature. ```go package main import ( "crypto/hmac" "crypto/sha256" "encoding/base64" "fmt" ) func signURL(key, url string) string { mac := hmac.New(sha256.New, []byte(key)) mac.Write([]byte(url)) return base64.URLEncoding.EncodeToString(mac.Sum(nil)) } func main() { key := "secretkey" url := "https://example.com/image.jpg" sig := signURL(key, url) fmt.Printf("Signature: %s\n", sig) // Output: Signature: cw34eyalj8YvpLpETxSIxv2k8QkLel2UAR5Cku2FzGM= } ``` -------------------------------- ### Generate Signed Request in JavaScript Source: https://github.com/willnorris/imageproxy/wiki/URL-signing Sign a URL in JavaScript using the 'crypto' module for HMAC-SHA256 and 'urlsafe-base64' for encoding. Ensure you have these modules installed. ```javascript import crypto from 'crypto'; import URLSafeBase64 from 'urlsafe-base64'; let key = 'secret key'; let data = 'https://octodex.github.com/images/codercat.jpg'; console.log(URLSafeBase64.encode(crypto.createHmac('sha256', key).update(data).digest())); ``` -------------------------------- ### Nginx Reverse Proxy Configuration Source: https://context7.com/willnorris/imageproxy/llms.txt Configure Nginx to proxy requests to imageproxy, setting necessary headers and cache validity. This example proxies requests at the `/api/imageproxy/` path. ```nginx # Proxy imageproxy at /api/imageproxy/ location /api/imageproxy/ { proxy_pass http://localhost:8080/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_cache_valid 200 1d; } # With higher precedence location ^~ /api/imageproxy/ { proxy_pass http://localhost:8080/; } ``` -------------------------------- ### Caddy Reverse Proxy Configuration Source: https://context7.com/willnorris/imageproxy/llms.txt Configure Caddy to act as a reverse proxy for imageproxy, rewriting the URI and forwarding requests. This setup assumes imageproxy is running on localhost:8080. ```caddyfile # Reverse proxy configuration @imageproxy path /api/imageproxy/* handle @imageproxy { uri replace /api/imageproxy/ / reverse_proxy http://localhost:8080 } # Embedded module configuration (requires custom Caddy build) @imageproxy path /api/imageproxy/* handle @imageproxy { uri replace /api/imageproxy/ / imageproxy { cache /data/imageproxy-cache default_base_url https://cdn.example.com/ allow_hosts example.com,*.cdn.example.com signature_key {$IMAGEPROXY_SIGNATUREKEY} } } ``` -------------------------------- ### Generate Signed Request in Python Source: https://github.com/willnorris/imageproxy/wiki/URL-signing Generate a signed URL using Python's built-in hmac, hashlib, and base64 modules. This example uses a placeholder secret key and image URL. ```python import hmac import hashlib import base64 key = 'secret key' data = 'https://octodex.github.com/images/codercat.jpg' print base64.urlsafe_b64encode(hmac.new(key, msg=data, digestmod=hashlib.sha256).digest()) ``` -------------------------------- ### Crop Image to Specific Rectangle Source: https://context7.com/willnorris/imageproxy/llms.txt Crops an image to a rectangle of 400x300 pixels, starting at coordinates (175,0). The 'cx', 'cy', 'cw', 'ch' parameters define the crop area. ```bash curl "http://localhost:8080/cx175,cy0,cw400,ch300/https://example.com/image.jpg" -o crop1.jpg ``` -------------------------------- ### Configure and Run Imageproxy Server in Go Source: https://context7.com/willnorris/imageproxy/llms.txt Set up a Go application to serve images through imageproxy. Configure allowed/denied hosts, referrers, signature keys, scaling, timeouts, content types, user agent, base URL, and logging. ```go package main import ( "log" "net/http" "net/url" "time" "github.com/die-net/lrucache" "willnorris.com/go/imageproxy" ) func main() { // Create cache (100MB in-memory) cache := lrucache.New(100*1024*1024, 0) // Create proxy with cache p := imageproxy.NewProxy(nil, cache) // Configure allowed hosts p.AllowHosts = []string{"example.com", "*.cdn.example.com"} // Configure denied hosts (including private networks) p.DenyHosts = []string{"192.168.0.0/16", "10.0.0.0/8", "internal.example.com"} // Require specific referrers p.Referrers = []string{"myapp.com", "*.myapp.com"} // Set signature key for signed requests p.SignatureKeys = [][]byte{[]byte("my-secret-key")} // Allow images to scale beyond original size p.ScaleUp = true // Set request timeout p.Timeout = 30 * time.Second // Restrict content types p.ContentTypes = []string{"image/*"} // Set custom user agent p.UserAgent = "MyApp/1.0 imageproxy" // Set base URL for relative paths p.DefaultBaseURL, _ = url.Parse("https://cdn.example.com/") // Enable verbose logging p.Verbose = true // Start server log.Println("Starting imageproxy on :8080") log.Fatal(http.ListenAndServe(":8080", p)) } ``` -------------------------------- ### Docker Run with Environment Variables Source: https://context7.com/willnorris/imageproxy/llms.txt Configure imageproxy using environment variables for cache location, allowed hosts, and signature key. Mounts a volume for persistent cache. ```bash # With environment variables docker run -p 8080:8080 \ -e IMAGEPROXY_CACHE=/data/cache \ -e IMAGEPROXY_ALLOWHOSTS="example.com,cdn.example.com" \ -e IMAGEPROXY_SIGNATUREKEY="mysecretkey" \ -v /var/imageproxy-cache:/data/cache \ ghcr.io/willnorris/imageproxy -addr 0.0.0.0:8080 ``` -------------------------------- ### Configure Imageproxy Entrypoint in Dockerfile Source: https://github.com/willnorris/imageproxy/blob/main/README.md Set the entrypoint for the imageproxy Docker image to specify the address. Ensure the container user has write permissions to any bind-mounted cache directories. ```Dockerfile ENTRYPOINT ["/app/imageproxy", "-addr 0.0.0.0:8080"] ``` -------------------------------- ### Resize with custom quality Source: https://context7.com/willnorris/imageproxy/llms.txt Apply resizing and set a custom JPEG quality simultaneously. ```bash curl "http://localhost:8080/500x,q75/https://example.com/image.jpg" -o resized_q75.jpg ``` -------------------------------- ### Enable Signed Requests Source: https://github.com/willnorris/imageproxy/blob/main/README.md Run imageproxy with the -signatureKey flag to enforce signed requests. The key can be provided directly or loaded from a file using the '@' prefix. ```sh imageproxy -signatureKey "secretkey" ``` -------------------------------- ### Register Plugin Function Source: https://github.com/willnorris/imageproxy/blob/main/docs/plugin-design.md Plugins are registered by importing their package and calling `imageproxy.RegisterPlugin` within an `init` function. This function takes a plugin name and a Plugin struct. ```go type Plugin struct { } func RegisterPlugin(name string, plugin Plugin) ``` -------------------------------- ### Sign URL with options Source: https://context7.com/willnorris/imageproxy/llms.txt To sign a URL that includes transformation options, first construct the canonical URL with options appended after a '#', then sign this canonical URL. The signature is then appended to the options in the final request URL. ```bash imageproxy-sign -key "secretkey" "https://example.com/image.jpg#400x400,q40" ``` -------------------------------- ### Crop and Resize Image Source: https://context7.com/willnorris/imageproxy/llms.txt First crops an image to a 100x100 pixel area from the top-left corner, then resizes the cropped portion to 50x50 pixels. ```bash curl "http://localhost:8080/cw100,ch100,50x/https://example.com/image.jpg" -o crop_resize.jpg ``` -------------------------------- ### Resize and convert to PNG Source: https://context7.com/willnorris/imageproxy/llms.txt Perform resizing and convert the image to PNG format in a single operation. ```bash curl "http://localhost:8080/200x,png/https://example.com/image.jpg" -o resized.png ``` -------------------------------- ### Generate signature using imageproxy-sign tool Source: https://context7.com/willnorris/imageproxy/llms.txt Use the 'imageproxy-sign' command-line tool to generate HMAC-SHA256 signatures for URLs. Provide the key and the URL to sign. ```bash imageproxy-sign -key "secretkey" "https://example.com/image.jpg" ``` -------------------------------- ### Final URL with signed options Source: https://context7.com/willnorris/imageproxy/llms.txt Construct the final URL by including the transformation options and the signature generated for the canonical URL. ```bash curl "http://localhost:8080/400x400,q40,s0sR2kjyfiF1RQRj4Jm2fFa3_6SDFqdAaDEmy1oD2U-4=/https://example.com/image.jpg" -o signed_opts.jpg ``` -------------------------------- ### Parse Image Transformation Options in Go Source: https://context7.com/willnorris/imageproxy/llms.txt Programmatically parse and manipulate image transformation options using the `Options` struct and `ParseOptions` function. Supports dimensions, rotation, quality, cropping, smart cropping, format conversion, and percentage-based sizing. ```go package main import ( "fmt" "willnorris.com/go/imageproxy" ) func main() { // Parse options from string opt := imageproxy.ParseOptions("200x150,r90,q80,fit") fmt.Printf("Width: %v, Height: %v\n", opt.Width, opt.Height) // Width: 200, Height: 150 fmt.Printf("Rotate: %d, Quality: %d\n", opt.Rotate, opt.Quality) // Rotate: 90, Quality: 80 fmt.Printf("Fit: %v\n", opt.Fit) // Fit: true // Parse crop options cropOpt := imageproxy.ParseOptions("cx100,cy50,cw200,ch150") fmt.Printf("Crop: x=%v y=%v w=%v h=%v\n", cropOpt.CropX, cropOpt.CropY, cropOpt.CropWidth, cropOpt.CropHeight) // Crop: x=100 y=50 w=200 h=150 // Parse smart crop scOpt := imageproxy.ParseOptions("300x200,sc") fmt.Printf("SmartCrop: %v\n", scOpt.SmartCrop) // SmartCrop: true // Parse format conversion fmtOpt := imageproxy.ParseOptions("png") fmt.Printf("Format: %s\n", fmtOpt.Format) // Format: png // Build options programmatically opts := imageproxy.Options{ Width: 300, Height: 200, Fit: true, Quality: 85, Format: "jpeg", } fmt.Printf("Options string: %s\n", opts.String()) // Output: 300x200,fit,jpeg,q85 // Parse percentage-based dimensions pctOpt := imageproxy.ParseOptions("0.5x0.25") fmt.Printf("Width: %v (50%%), Height: %v (25%%)\n", pctOpt.Width, pctOpt.Height) } ``` -------------------------------- ### Configure On-Disk Cache with Environment Variable Source: https://github.com/willnorris/imageproxy/blob/main/README.md Configure an on-disk cache for imageproxy by setting the IMAGEPROXY_CACHE environment variable. This is useful for persistent caching across restarts. ```sh IMAGEPROXY_CACHE="/tmp/imageproxy" imageproxy ``` -------------------------------- ### Create a Square Thumbnail Source: https://context7.com/willnorris/imageproxy/llms.txt Creates a square thumbnail of an image. The single dimension specified (100px) is used for both width and height, and the image is cropped to fit. ```bash curl "http://localhost:8080/100/https://example.com/image.jpg" -o square.jpg ``` -------------------------------- ### Configure Tiered Caching with Memory and GCS Source: https://github.com/willnorris/imageproxy/blob/main/README.md Sets up a tiered caching system where imageproxy first checks an in-memory cache, then a Google Cloud Storage bucket. This optimizes access speed by prioritizing faster storage. ```sh imageproxy -cache memory -cache gcs://my-bucket/ ``` -------------------------------- ### Create Square Thumbnail (150px) Source: https://context7.com/willnorris/imageproxy/llms.txt Creates a square thumbnail of an image with dimensions of 150x150 pixels. The single dimension specified is used for both width and height, and the image is cropped. ```bash curl "http://localhost:8080/150/https://example.com/image.jpg" -o thumb.jpg ``` -------------------------------- ### Resize Image to Exact Dimensions (Crop to Fit) Source: https://context7.com/willnorris/imageproxy/llms.txt Proxies and resizes an image to exact dimensions of 100x150 pixels, cropping the image as necessary to fit these dimensions. ```bash curl "http://localhost:8080/100x150/https://example.com/image.jpg" -o cropped.jpg ``` -------------------------------- ### Use signed URL Source: https://context7.com/willnorris/imageproxy/llms.txt Construct a signed URL by appending the generated signature to the 's' parameter. This secures the request against unauthorized use. ```bash curl "http://localhost:8080/scw34eyalj8YvpLpETxSIxv2k8QkLel2UAR5Cku2FzGM=/https://example.com/image.jpg" -o signed.jpg ``` -------------------------------- ### Smart crop Source: https://context7.com/willnorris/imageproxy/llms.txt Utilize content-aware smart cropping by appending ',sc' to the URL. This is useful for automatically identifying and cropping the most important part of an image. ```bash curl "http://localhost:8080/200x300,sc/https://example.com/portrait.jpg" -o smart.jpg ``` -------------------------------- ### Embed Imageproxy in Caddy with Custom Build Source: https://github.com/willnorris/imageproxy/blob/main/README.md Embed imageproxy directly within Caddy using a custom build and the 'imageproxy' directive. This requires building Caddy with the imageproxy module and configuring directives like cache, default_base_url, allow_hosts, and signature_key via environment variables. ```Caddyfile @imageproxy path /api/imageproxy/* handle @imageproxy { uri replace /api/imageproxy/ / imageproxy { cache /data/imageproxy-cache default_base_url {$IMAGEPROXY_BASEURL} allow_hosts {$IMAGEPROXY_ALLOWHOSTS} signature_key {$IMAGEPROXY_SIGNATUREKEY} } } ``` -------------------------------- ### Time-limited URL Source: https://context7.com/willnorris/imageproxy/llms.txt Create time-limited URLs by including a 'vu' parameter followed by a Unix timestamp, and then signing the URL. The signature prevents tampering with the expiration time. ```bash curl "http://localhost:8080/200x,vu1800000000,s=/https://example.com/image.jpg" -o timelimited.jpg ``` -------------------------------- ### Proxy Image Without Transformation Source: https://context7.com/willnorris/imageproxy/llms.txt Fetches and serves an image from a remote URL without applying any transformations. This is achieved by providing an empty options string. ```bash curl "http://localhost:8080//https://example.com/image.jpg" -o proxied.jpg ``` -------------------------------- ### Percentage Resize (25% Width and Height) Source: https://context7.com/willnorris/imageproxy/llms.txt Resizes an image to 25% of its original width and 25% of its original height, maintaining the aspect ratio. ```bash curl "http://localhost:8080/0.25x0.25/https://example.com/image.jpg" -o quarter.jpg ``` -------------------------------- ### Response Authorizer Interface Source: https://github.com/willnorris/imageproxy/blob/main/docs/plugin-design.md Implement this interface for plugins that need to authorize responses from a remote server before they are returned to a client. The `AuthorizeResponse` method should return an error if the response is not permitted. ```go // A ResponseAuthorizer determines if a response from a remote server // is authorized to be returned. type ResponseAuthorizer interface { // AuthorizeResponse returns an error if a response should not be // returned to a client (for example, it is not for an image // resource, etc). AuthorizeResponse(res http.Response) error } ``` -------------------------------- ### Resize and rotate image Source: https://context7.com/willnorris/imageproxy/llms.txt Combine resizing with rotation in one request. The order of operations matters; here, resizing is applied before rotation. ```bash curl "http://localhost:8080/200x,r90/https://example.com/image.jpg" -o resize_rotate.jpg ``` -------------------------------- ### Enable Scaling Beyond Original Size Source: https://github.com/willnorris/imageproxy/blob/main/README.md Use the -scaleUp flag set to true to allow imageproxy to scale images larger than their original dimensions. ```sh imageproxy -scaleUp true ``` -------------------------------- ### Imageproxy Health Check and Metrics Endpoints Source: https://context7.com/willnorris/imageproxy/llms.txt Access the health check and Prometheus metrics endpoints for imageproxy. The root path also returns 'OK'. ```bash # Health check endpoint curl http://localhost:8080/health-check # Output: OK # Root path also returns OK curl http://localhost:8080/ # Output: OK # Prometheus metrics endpoint curl http://localhost:8080/metrics # Output: Prometheus-formatted metrics including: # - imageproxy_requests_in_flight # - imageproxy_request_duration_seconds # - imageproxy_remote_errors_total # - imageproxy_served_from_cache_total # - imageproxy_transformation_duration_seconds ``` -------------------------------- ### Request Authorizer Interface Source: https://github.com/willnorris/imageproxy/blob/main/docs/plugin-design.md Implement this interface for plugins that need to authorize requests before the remote resource is retrieved. The `AuthorizeRequest` method should return an error if the request is not permitted. ```go // A RequestAuthorizer determines if a request is authorized to be processed. // Requests are processed before the remote resource is retrieved. type RequestAuthorizer interface { // Authorize returns an error if the request should not // be processed further (for example, it doesn't have a // valid signature, is not for a whitelisted host, etc). AuthorizeRequest(req *http.Request) error } ``` -------------------------------- ### Generate Signed Request with OpenSSL Source: https://github.com/willnorris/imageproxy/wiki/URL-signing Utilize the OpenSSL command-line tool to generate a signed URL. This method is useful for shell scripting and quick testing. ```shell $ echo -n "https://www.google.fr/images/srpr/logo11w.png" | openssl dgst -sha256 -hmac "test" -binary|base64| tr '/+' '_-' RYifAJRfbhsitJeOrDNxWURCCkPsVR4ihCPXNv-ePbA= ``` -------------------------------- ### Go program to generate HMAC-SHA256 signature Source: https://github.com/willnorris/imageproxy/blob/main/docs/url-signing.md This Go program calculates the HMAC-SHA256 hash of a given URL using a secret key. It then base64 encodes the result in a URL-safe manner. Use this to generate signatures for imageproxy requests. ```go package main import ( "os" "fmt" "crypto/hmac" "crypto/sha256" "encoding/base64" ) func main() { key, url := os.Args[1], os.Args[2] mac := hmac.New(sha256.New, []byte(key)) mac.Write([]byte(url)) result := mac.Sum(nil) fmt.Println(base64.URLEncoding.EncodeToString(result)) } ``` ```shell $ go run sign.go "secretkey" "https://octodex.github.com/images/codercat.jpg" cw34eyalj8YvpLpETxSIxv2k8QkLel2UAR5Cku2FzGM= ``` -------------------------------- ### Combine rotation and flipping Source: https://context7.com/willnorris/imageproxy/llms.txt Apply multiple transformations like rotation and flipping in a single request. Rotation is applied before flipping. ```bash curl "http://localhost:8080/r90,fh,fv/https://example.com/image.jpg" -o rotated_flipped.jpg ``` -------------------------------- ### Convert image to PNG Source: https://context7.com/willnorris/imageproxy/llms.txt Convert an image to PNG format by specifying 'png' in the URL. ```bash curl "http://localhost:8080/png/https://example.com/image.jpg" -o converted.png ``` -------------------------------- ### Convert image to TIFF Source: https://context7.com/willnorris/imageproxy/llms.txt Convert an image to TIFF format by specifying 'tiff' in the URL. ```bash curl "http://localhost:8080/tiff/https://example.com/image.jpg" -o converted.tiff ``` -------------------------------- ### Set JPEG quality Source: https://context7.com/willnorris/imageproxy/llms.txt Control the output quality for JPEG images using the 'q' option. The default quality is 95%. ```bash curl "http://localhost:8080/q60/https://example.com/image.jpg" -o low_quality.jpg ``` -------------------------------- ### Run Imageproxy Docker Container Source: https://github.com/willnorris/imageproxy/blob/main/README.md Run the official imageproxy Docker image, exposing port 8080 and binding it to all interfaces. This is a common way to deploy imageproxy in containerized environments. ```sh docker run -p 8080:8080 ghcr.io/willnorris/imageproxy -addr 0.0.0.0:8080 ``` -------------------------------- ### Process WebP input (auto-convert to JPEG) Source: https://context7.com/willnorris/imageproxy/llms.txt The imageproxy can process WebP images. By default, they are auto-converted to JPEG for transformation. ```bash curl "http://localhost:8080/200x/https://example.com/image.webp" -o from_webp.jpg ``` -------------------------------- ### Proxy Image with Query String in Remote URL Source: https://context7.com/willnorris/imageproxy/llms.txt Proxies an image from a remote URL that includes query parameters. The imageproxy server passes these parameters along to the origin server. ```bash curl "http://localhost:8080/200x/https://example.com/image.jpg?token=abc123" -o withquery.jpg ``` -------------------------------- ### Configure nginx Location Precedence for Imageproxy Source: https://github.com/willnorris/imageproxy/blob/main/README.md Adjust nginx location precedence using '^~' to ensure requests to '/api/imageproxy/' are handled by imageproxy. This is useful when other location directives might conflict. ```nginx location ^~ /api/imageproxy/ { proxy_pass http://localhost:4593/; } ``` -------------------------------- ### Configure Disk Cache for Imageproxy Source: https://github.com/willnorris/imageproxy/blob/main/README.md Enables caching of images to a specified directory on the local disk. This is useful for persistent storage of processed images. ```sh imageproxy -cache /tmp/imageproxy ``` -------------------------------- ### Resize Image to Exact Dimensions (Crop) Source: https://context7.com/willnorris/imageproxy/llms.txt Resizes an image to exact dimensions of 300x200 pixels, cropping the image as necessary to fit these dimensions. ```bash curl "http://localhost:8080/300x200/https://example.com/image.jpg" -o exact.jpg ``` -------------------------------- ### Percentage Resize (50% Width) Source: https://context7.com/willnorris/imageproxy/llms.txt Resizes an image to 50% of its original width, maintaining the aspect ratio for the height. The remote URL is provided directly. ```bash curl "http://localhost:8080/0.5x/https://example.com/image.jpg" -o half.jpg ``` -------------------------------- ### Image Transformer Interface Source: https://github.com/willnorris/imageproxy/blob/main/docs/plugin-design.md Implement this interface for plugins that transform images. The `TransformImage` method takes an image and options, and returns the transformed image. ```go // An ImageTransformer transforms an image. type ImageTransformer interface { // TransformImage based on the provided options and return the result. TransformImage(m image.Image, opt Options) image.Image } ``` -------------------------------- ### Resize Image to 200px Width (Proportional Height) Source: https://context7.com/willnorris/imageproxy/llms.txt Proxies and resizes an image to a width of 200 pixels, maintaining the original aspect ratio for the height. The remote URL is provided directly. ```bash curl "http://localhost:8080/200x/https://example.com/image.jpg" -o resized.jpg ``` -------------------------------- ### Percentage-based crop Source: https://context7.com/willnorris/imageproxy/llms.txt Crop using percentage values for cx, cy, cw, and ch to define the crop area relative to the image dimensions. ```bash curl "http://localhost:8080/cx0.25,cy0.25,cw0.5,ch0.5/https://example.com/image.jpg" -o center.jpg ``` -------------------------------- ### Transform Image Bytes Directly in Go Source: https://context7.com/willnorris/imageproxy/llms.txt Use the `Transform` function to directly manipulate image bytes without running a server. Supports resizing, rotation, flipping, format conversion, and smart cropping. ```go package main import ( "fmt" "os" "willnorris.com/go/imageproxy" ) func main() { // Read source image img, err := os.ReadFile("input.jpg") if err != nil { panic(err) } // Define transformation options opts := imageproxy.Options{ Width: 800, Height: 600, Fit: true, Quality: 85, } // Transform the image result, err := imageproxy.Transform(img, opts) if err != nil { panic(err) } // Write transformed image err = os.WriteFile("output.jpg", result, 0644) if err != nil { panic(err) } fmt.Printf("Transformed %d bytes to %d bytes\n", len(img), len(result)) // Rotate and flip rotateOpts := imageproxy.Options{ Rotate: 90, FlipHorizontal: true, } rotated, _ := imageproxy.Transform(img, rotateOpts) os.WriteFile("rotated.jpg", rotated, 0644) // Convert format pngOpts := imageproxy.Options{ Width: 400, Format: "png", } pngImg, _ := imageproxy.Transform(img, pngOpts) os.WriteFile("converted.png", pngImg, 0644) // Smart crop for thumbnails thumbOpts := imageproxy.Options{ Width: 150, Height: 150, SmartCrop: true, } thumb, _ := imageproxy.Transform(img, thumbOpts) os.WriteFile("thumbnail.jpg", thumb, 0644) } ``` -------------------------------- ### Allow Specific Hosts Source: https://github.com/willnorris/imageproxy/blob/main/README.md Use the -allowHosts flag to restrict image fetching to specified domains. Supports comma-separated lists and wildcard subdomains. ```sh imageproxy -allowHosts example.com ``` -------------------------------- ### Percentage-Based Resize (Height) Source: https://context7.com/willnorris/imageproxy/llms.txt Resizes an image to 15% of its original height, maintaining the aspect ratio for the width. The remote URL is provided directly. ```bash curl "http://localhost:8080/x0.15/https://example.com/image.jpg" -o small.jpg ``` -------------------------------- ### Set Default Base URL Source: https://github.com/willnorris/imageproxy/blob/main/README.md Use the -baseURL flag to specify a default base URL for relative image paths. This simplifies requests for images from a common source. ```sh imageproxy -baseURL https://octodex.github.com/ ``` -------------------------------- ### Signed URL with Expiration Source: https://github.com/willnorris/imageproxy/blob/main/README.md Include the 'vu' option with a Unix timestamp in a signed URL to set an expiration time. The URL will only be valid until the specified timestamp. ```http http://localhost:8080/vu1577836800,sjNcVf6LxzKEvR6Owgg3zhEMN7xbWxlpf-eyYbRfFK4A=/https://example.com/image ``` -------------------------------- ### Enable Allowed Referrer List Source: https://github.com/willnorris/imageproxy/blob/main/README.md Restricts image access to only those originating from specified domains in the HTTP referrer header. This helps prevent hotlinking and unauthorized use of images. ```sh imageproxy -referrers example.com ``` -------------------------------- ### Scale Image to Fit Within Dimensions (No Cropping) Source: https://context7.com/willnorris/imageproxy/llms.txt Resizes an image to fit within a 200x200 pixel box without cropping, preserving the aspect ratio. The 'fit' option ensures the image scales down to fit. ```bash curl "http://localhost:8080/200x200,fit/https://example.com/image.jpg" -o fitted.jpg ``` -------------------------------- ### Sign URL with Ruby Source: https://github.com/willnorris/imageproxy/blob/main/docs/url-signing.md This Ruby script signs a URL using HMAC-SHA256 and Base64 URL-safe encoding. It requires the 'openssl' and 'base64' libraries. ```ruby require 'openssl' require 'base64' key = ARGV[0] url = ARGV[1] puts Base64.urlsafe_encode64(OpenSSL::HMAC.digest(OpenSSL::Digest.new('sha256'), key, url)).strip() ``` ```shell % ruby sign.rb "secretkey" "https://octodex.github.com/images/codercat.jpg" ``` -------------------------------- ### Fit Image Within Box (Preserve Aspect Ratio) Source: https://context7.com/willnorris/imageproxy/llms.txt Scales an image to fit within a 300x200 pixel box without cropping, preserving the aspect ratio. The 'fit' option ensures the image scales down to fit. ```bash curl "http://localhost:8080/300x200,fit/https://example.com/image.jpg" -o fit.jpg ``` -------------------------------- ### Generate Signed Request Source: https://github.com/willnorris/imageproxy/blob/main/README.md Sign remote URLs using HMAC-SHA256 and URL-safe base64 encoding. The -signatureKey flag specifies the secret key for signing. ```go base64urlencode(hmac.New(sha256, ).digest()) ``` -------------------------------- ### Sign URL with PHP Source: https://github.com/willnorris/imageproxy/blob/main/docs/url-signing.md A PHP script for signing URLs using HMAC-SHA256 and Base64 encoding. It manually replaces characters to achieve URL-safe encoding. ```php ``` ```shell $ php ex.php RYifAJRfbhsitJeOrDNxWURCCkPsVR4ihCPXNv-ePbA= ``` -------------------------------- ### Crop from bottom edge Source: https://context7.com/willnorris/imageproxy/llms.txt Use negative cy values to crop from the bottom edge of the image. ```bash curl "http://localhost:8080/cy-50,cw200,ch50/https://example.com/image.jpg" -o bottom_crop.jpg ``` -------------------------------- ### Force JPEG output from WebP Source: https://context7.com/willnorris/imageproxy/llms.txt Explicitly force JPEG output when processing a WebP image by including ',jpeg' in the URL. ```bash curl "http://localhost:8080/200x,jpeg/https://example.com/image.webp" -o webp_to_jpeg.jpg ``` -------------------------------- ### Resize Image by Width Only Source: https://context7.com/willnorris/imageproxy/llms.txt Resizes an image to a specific width (300 pixels), automatically calculating the proportional height to maintain the aspect ratio. ```bash curl "http://localhost:8080/300x/https://example.com/image.jpg" -o w300.jpg ``` -------------------------------- ### Set Minimum Cache Duration Source: https://github.com/willnorris/imageproxy/blob/main/README.md Configures imageproxy to enforce a minimum cache duration for all cached images, overriding shorter durations specified in response headers. This ensures images remain cached for at least the specified time, unless explicitly set to not cache. ```sh imageproxy -cache /tmp/imageproxy -minCacheDuration 5m ``` -------------------------------- ### OpenSSL command for HMAC-SHA256 signature Source: https://github.com/willnorris/imageproxy/blob/main/docs/url-signing.md This OpenSSL command calculates the HMAC-SHA256 hash of a given URL using a secret key. It pipes the output to base64 for encoding and then uses 'tr' to make it URL-safe. This is an alternative to using a programming language for signature generation. ```shell $ echo -n "https://octodex.github.com/images/codercat.jpg" | openssl dgst -sha256 -hmac "secretkey" -binary|base64| tr '/+' '_-' cw34eyalj8YvpLpETxSIxv2k8QkLel2UAR5Cku2FzGM= ``` -------------------------------- ### Sign URL with Java Source: https://github.com/willnorris/imageproxy/blob/main/docs/url-signing.md Use this Java code to sign a URL with a secret key using HMAC-SHA256. Ensure you have the necessary Java Cryptography Architecture extensions. ```java import java.util.Base64; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; class SignUrl { public static String sign(String key, String url) throws Exception { Mac sha256_HMAC = Mac.getInstance("HmacSHA256"); SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(), "HmacSHA256"); sha256_HMAC.init(secret_key); return Base64.getUrlEncoder().encodeToString(sha256_HMAC.doFinal(url.getBytes())); } public static void main(String [] args) throws Exception { System.out.println(sign(args[0], args[1])); } } ``` ```shell $ javac SignUrl.java && java SignUrl "secretkey" "https://octodex.github.com/images/codercat.jpg" ``` -------------------------------- ### Resize Image by Height Only Source: https://context7.com/willnorris/imageproxy/llms.txt Resizes an image to a specific height (200 pixels), automatically calculating the proportional width to maintain the aspect ratio. ```bash curl "http://localhost:8080/x200/https://example.com/image.jpg" -o h200.jpg ``` -------------------------------- ### Generate Signed Request in Java Source: https://github.com/willnorris/imageproxy/wiki/URL-signing Implement signed URL generation in Java using Apache Commons Codec for Base64 encoding and standard Java crypto libraries for HMAC-SHA256. Ensure the commons-codec library is in your classpath. ```java import org.apache.commons.codec.binary.Base64; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; class EncodeUrl { public static String encode(String key, String data) throws Exception { Mac sha256_HMAC = Mac.getInstance("HmacSHA256"); SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(), "HmacSHA256"); sha256_HMAC.init(secret_key); return Base64.encodeBase64URLSafeString(sha256_HMAC.doFinal(data.getBytes())); } public static void main(String [] args) throws Exception { System.out.println(encode(args[0], args[1])); } } ``` ```shell $ java -cp commons-codec-1.10.jar:. EncodeUrl test https://www.google.fr/images/srpr/logo11w.png RYifAJRfbhsitJeOrDNxWURCCkPsVR4ihCPXNv-ePbA ``` -------------------------------- ### Sign URL with Python Source: https://github.com/willnorris/imageproxy/blob/main/docs/url-signing.md A Python script to sign a URL using HMAC-SHA256. It utilizes the 'base64', 'hashlib', and 'hmac' modules. Note the use of 'print' without parentheses, indicating Python 2. ```python import base64 import hashlib import hmac import sys key = sys.argv[1] url = sys.argv[2] print base64.urlsafe_b64encode(hmac.new(key, msg=url, digestmod=hashlib.sha256).digest()) ``` ```shell $ python sign.py "secretkey" "https://octodex.github.com/images/codercat.jpg" ``` -------------------------------- ### Flip image vertically Source: https://context7.com/willnorris/imageproxy/llms.txt Flip an image vertically using the 'fv' option. ```bash curl "http://localhost:8080/fv/https://example.com/image.jpg" -o flip_v.jpg ``` -------------------------------- ### Rotate image 90 degrees counter-clockwise Source: https://context7.com/willnorris/imageproxy/llms.txt Rotate an image 90 degrees counter-clockwise using the 'r90' option. ```bash curl "http://localhost:8080/r90/https://example.com/image.jpg" -o r90.jpg ``` -------------------------------- ### Rotate image 270 degrees Source: https://context7.com/willnorris/imageproxy/llms.txt Rotate an image 270 degrees counter-clockwise (or -90 degrees) using the 'r270' option. ```bash curl "http://localhost:8080/r270/https://example.com/image.jpg" -o r270.jpg ``` -------------------------------- ### Trim solid color borders Source: https://context7.com/willnorris/imageproxy/llms.txt Remove solid color borders from an image by using the 'trim' option. This is useful for cleaning up images with unnecessary padding. ```bash curl "http://localhost:8080/trim/https://example.com/bordered.jpg" -o trimmed.jpg ``` -------------------------------- ### Generate Signed Request in Ruby Source: https://github.com/willnorris/imageproxy/wiki/URL-signing Create signed URLs in Ruby using the OpenSSL library for HMAC-SHA256 and Base64 for URL-safe encoding. This snippet assumes the secret key and data are hardcoded for demonstration. ```ruby require 'openssl' require 'base64' key = "test" data = "https://www.google.fr/images/srpr/logo11w.png" puts Base64.urlsafe_encode64(OpenSSL::HMAC.digest(OpenSSL::Digest.new('sha256'), key, data)).strip() ``` ```shell % ruby sign.rb RYifAJRfbhsitJeOrDNxWURCCkPsVR4ihCPXNv-ePbA= ``` -------------------------------- ### Deny Specific Hosts Source: https://github.com/willnorris/imageproxy/blob/main/README.md Use the -denyHosts flag to prevent image fetching from specified domains. Supports comma-separated lists and wildcard subdomains. ```sh imageproxy -denyHosts octodex.github.com ``` -------------------------------- ### Crop from right edge Source: https://context7.com/willnorris/imageproxy/llms.txt Use negative cx values to crop from the right edge of the image. ```bash curl "http://localhost:8080/cx-100,cw100,ch200/https://example.com/image.jpg" -o right_crop.jpg ``` -------------------------------- ### Flip image horizontally Source: https://context7.com/willnorris/imageproxy/llms.txt Flip an image horizontally using the 'fh' option. ```bash curl "http://localhost:8080/fh/https://example.com/image.jpg" -o flip_h.jpg ``` -------------------------------- ### Rotate image 180 degrees Source: https://context7.com/willnorris/imageproxy/llms.txt Rotate an image 180 degrees using the 'r180' option. ```bash curl "http://localhost:8080/r180/https://example.com/image.jpg" -o r180.jpg ``` -------------------------------- ### Proxy Image with URL-Encoded Remote URL Source: https://context7.com/willnorris/imageproxy/llms.txt Proxies an image where the remote URL is percent-encoded. This is useful when the URL contains special characters that could interfere with HTTP routing. ```bash curl "http://localhost:8080/200x/https%3A%2F%2Fexample.com%2Fimage.jpg" -o encoded.jpg ```