Skip to content

API Reference

This page is the complete API surface of the package. If you are looking for guidance on how to use these methods, start with the Basic Usage documentation instead.

The imgproxy() Helper

php
function imgproxy(): Manager

Returns the Manager instance, a terse alternative to the facade. Defined globally in src/helpers.php.

php
imgproxy()->image('https://example.com/image.jpg')->width(800)->url();

The Imgproxy Facade

Imsus\LaravelImgproxy\Imgproxy proxies to the Manager singleton. It is deliberately not final, so applications can mock it with the standard Imgproxy::shouldReceive(...) pattern.

MethodSignatureDescription
imageimage(string $source, ?string $instance = null): BuilderBuild a URL for the given source on the default (or named) instance.
instanceinstance(?string $name = null): InstanceResolve a named imgproxy instance.
defaultInstancedefaultInstance(): stringThe name of the default imgproxy instance.

Manager

Imsus\LaravelImgproxy\Manager resolves imgproxy instances from the published config file.

php
Imgproxy::instance('staging');           // resolve a named instance
Imgproxy::image('https://...');            // build on the default instance
Imgproxy::image('https://...', 'staging'); // build on a named instance

Builder

Imsus\LaravelImgproxy\Builder is the immutable fluent builder. Every option method returns a new instance; url() and __toString() are terminal.

Construction & Terminal

php
public function __construct(
    string $baseUrl,
    string $source,
    string $encoding = 'base64',
    array $segments = [],
    ?string $key = null,
    ?string $salt = null,
    ?int $signatureSize = null,
    array $presets = [],
)
MethodSignatureimgproxy segmentDescription
__construct__construct(string $baseUrl, string $source, string $encoding = 'base64', array $segments = [], ?string $key = null, ?string $salt = null, ?int $signatureSize = null, array $presets = [])Create a builder with the given base URL, source, encoding, signing credentials, and preset option sets.
urlurl(): stringThe full imgproxy URL.
__toString__toString(): stringAlias for url(). Works in string contexts.
sourceEncodingsourceEncoding(string $encoding): selfReturn a copy with a different source encoding (base64 or plain).
diskdisk(string $disk, string $path, int|DateTimeInterface|null $expiration = null): selfSet the source to a file on a Storage disk. Public disks use url(); private disks use a pre-signed temporaryUrl().
toStorage v2.1.0toStorage(string $disk, string $path, array $options = []): StoredImageFetch the processed image from imgproxy and write it to a Storage disk, streaming the response body. Existing files are overwritten. Returns a StoredImage.

Resize

MethodSignatureimgproxy segmentDescription
resizeresize(ResizeType|string $type, ?int $width = null, ?int $height = null, bool $enlarge = false, bool $extend = false): selfrs:Resize the image with a type, dimensions, and optional enlarge/extend flags.
resizeWithGravityresizeWithGravity(?int $width = null, ?int $height = null, bool $enlarge = false, bool $extend = false, Gravity|string|null $gravity = null): selfs:Set width, height, enlarge, extend, and gravity in one option.
widthwidth(int $width): selfw:Set the width of the resulting image. 0 auto-calculates from height and aspect ratio.
heightheight(int $height): selfh:Set the height of the resulting image. 0 auto-calculates from width and aspect ratio.
minWidthminWidth(int $width): selfmw:Set the minimum width of the resulting image.
minHeightminHeight(int $height): selfmh:Set the minimum height of the resulting image.
zoomzoom(int|float $x, int|float|null $y = null): selfz:Multiply image dimensions by the given factors. Unlike dpr, does not affect gravity offsets.

Crop & Gravity

MethodSignatureimgproxy segmentDescription
cropcrop(int|float $width, int|float $height, Gravity|string|null $gravity = null): selfc:Define an area to crop before resize. Values below 1 are relative; 0 uses the full dimension.
trimtrim(float $threshold, ?string $color = null, bool $equalHorizontal = false, bool $equalVertical = false): selft:Remove the surrounding background. The color is 3 or 6 digit hex.
paddingpadding(int $top, ?int $right = null, ?int $bottom = null, ?int $left = null): selfpd:Add padding around the image using CSS-style syntax (sides default as in CSS).
gravitygravity(Gravity|string $gravity, int|float $xOffset = 0, int|float $yOffset = 0): selfg:Set the gravity used when imgproxy cuts parts of the image. Offsets emitted only when non-zero.
focusPointfocusPoint(float $x, float $y): selfg:fp:Set the gravity focus point. Offsets between 0 and 1 (left/right for x, top/bottom for y).

Quality & Format

MethodSignatureimgproxy segmentDescription
qualityquality(int $quality): selfq:Set the quality of the resulting image (0–100). 0 falls back to the server default.
formatformat(Format|string $format): selff:Set the resulting image format.
formatQualityformatQuality(array $qualities): selffq:Redefine quality for specific output formats. Keys are format values (e.g. 'webp'), values are 0–100.
skipProcessingskipProcessing(Format|string ...$formats): selfskp:Skip processing for the given source formats.
rawraw(): selfraw:Respond with the raw unprocessed source image.
withoutRawwithoutRaw(): selfraw:Disable raw response.

Effects

MethodSignatureimgproxy segmentDescription
blurblur(int|float $sigma): selfbl:Apply a Gaussian blur filter with the given sigma.
sharpensharpen(int|float $sigma): selfsh:Apply the sharpen filter with the given sigma.
pixelatepixelate(int $size): selfpix:Apply the pixelate filter with the given pixel size.
dprdpr(int|float $dpr): selfdpr:Multiply image dimensions for HiDPI (Retina) displays. Affects gravity offsets and paddings.
placeholderplaceholder(): selfw:16, bl:8, f:webpReturn a tiny blurred webp of the same source for LQIP placeholders. Chains width(16), blur(8), and format(Format::Webp).

Transform

MethodSignatureimgproxy segmentDescription
rotaterotate(int $angle): selfrot:Rotate the image by the given angle (must be a non-negative multiple of 90).
autoRotateautoRotate(): selfar:Automatically rotate based on the EXIF orientation.
withoutAutoRotatewithoutAutoRotate(): selfar:Disable automatic rotation.
flipflip(bool $horizontal = false, bool $vertical = false): selffl:Flip the image along the horizontal and/or vertical axes.
enlargeenlarge(): selfel:Enlarge the image when it is smaller than the given size.
withoutEnlargewithoutEnlarge(): selfel:Disable enlargement.
extendextend(Gravity|string|null $gravity = null): selfex:Extend the image when it is smaller than the given size. Smart gravity not supported.
withoutExtendwithoutExtend(): selfex:Disable extension.
extendAspectRatioextendAspectRatio(Gravity|string|null $gravity = null): selfexar:Extend the image to the requested aspect ratio. Smart gravity not supported.
withoutExtendAspectRatiowithoutExtendAspectRatio(): selfexar:Disable aspect ratio extension.

Background & Watermark

MethodSignatureimgproxy segmentDescription
backgroundbackground(string $color): selfbg:Fill the resulting image background with a 3 or 6 digit hex color.
watermarkwatermark(int|float $opacity, WatermarkPosition|string|null $position = null, int|float $xOffset = 0, int|float $yOffset = 0, int|float $scale = 0): selfwm:Place a watermark on the processed image. Opacity is 0–1 (exclusive 0). Scale of 0 leaves the watermark size unchanged.

Output

MethodSignatureimgproxy segmentDescription
stripMetadatastripMetadata(): selfsm:Strip the output image metadata (EXIF, IPTC, etc.).
withoutMetadatawithoutMetadata(): selfsm:Keep output image metadata.
keepCopyrightkeepCopyright(): selfkcr:Keep the copyright info while stripping metadata.
withoutCopyrightwithoutCopyright(): selfkcr:Strip copyright info along with metadata.
stripColorProfilestripColorProfile(): selfscp:Transform the embedded color profile to sRGB and remove it.
withoutColorProfilewithoutColorProfile(): selfscp:Keep the embedded color profile.
preserveHDRpreserveHDR(): selfph:Keep high bit images high bit instead of downscaling to 8 bit.
enforceThumbnailenforceThumbnail(): selfeth:Always use the embedded thumbnail of the source image when available.
returnAttachmentreturnAttachment(): selfatt:Return the processed image as an attachment instead of inline.
cacheBustercacheBuster(string $buster): selfcb:Add a cache buster to bypass CDN, proxy, and browser caches.
expiresexpires(int $timestamp): selfexp:Set the unix timestamp after which imgproxy returns 404. 0 disables expiration.
filenamefilename(string $filename, bool $encoded = false): selffn:Set the filename for the Content-Disposition header. Pass true for $encoded if the filename is already URL-safe base64.
presetpreset(string $name, string ...$more): selfpr:Apply server-side presets configured on the imgproxy instance. The server must have the preset registered.

Presets

MethodSignatureimgproxy segmentDescription
applyPresetapplyPreset(string $name): selfCompose a named preset from config onto the builder. Options are appended before any options chained after this call, so per-URL overrides win.

Security

MethodSignatureimgproxy segmentDescription
maxSourceResolutionmaxSourceResolution(int|float $megapixels): selfmsr:Redefine the maximum source image resolution in megapixels. Requires security options on the server.
maxSourceFileSizemaxSourceFileSize(int $bytes): selfmsfs:Redefine the maximum source image file size in bytes.
maxAnimationFramesmaxAnimationFrames(int $frames): selfmaf:Redefine the maximum number of animation frames.
maxAnimationFrameResolutionmaxAnimationFrameResolution(int|float $megapixels): selfmafr:Redefine the maximum animation frame resolution in megapixels.
maxResultDimensionmaxResultDimension(int $pixels): selfmrd:Redefine the maximum dimension of the resulting image in pixels.

Escape Hatch

MethodSignatureimgproxy segmentDescription
withOptionwithOption(string $segment): self(verbatim)Append a processing option segment verbatim, without validation. Use for imgproxy options not yet covered by a typed method.

StoredImage New in v2.1.0

Imsus\LaravelImgproxy\StoredImage is the representation of a processed image fetched from imgproxy and written to a Storage disk by Builder::toStorage(). It is immutable and holds only the disk name and path; the disk adapter and URLs resolve lazily.

MethodSignatureDescription
diskdisk(): stringThe destination disk name.
pathpath(): stringThe path of the stored image on the destination disk.
namename(): stringThe file name of the stored image.
urlurl(int|DateTimeInterface|null $expiration = null): stringA URL for the stored image: the plain object URL on public disks, a pre-signed temporaryUrl() on private ones (5 minutes by default).
adapteradapter(): FilesystemAdapterThe destination disk adapter, for advanced operations.
__toString__toString(): stringAlias for url(). Works in string contexts.

See Storage Integration for usage.

Enums

See the Enums Reference for the complete list of cases and their imgproxy segment mappings.

EnumNamespaceOptions
ResizeTypeImsus\LaravelImgproxy\Enums\ResizeTyperesize(), preset resize
GravityImsus\LaravelImgproxy\Enums\Gravitygravity(), crop(), resizeWithGravity(), extend(), extendAspectRatio()
FormatImsus\LaravelImgproxy\Enums\Formatformat(), formatQuality(), skipProcessing(), placeholder()
WatermarkPositionImsus\LaravelImgproxy\Enums\WatermarkPositionwatermark()

All enum arguments accept the enum instance or its string backing value interchangeably:

php
use Imsus\LaravelImgproxy\Enums\Gravity;

$imgproxy->gravity(Gravity::Smart);  // enum instance
$imgproxy->gravity('sm');            // string value — identical result

Blade Components

The <x-imgproxy-img> Component

Renders an <img> with a srcset built from width or DPR candidates, sizes, an LQIP placeholder, lazy loading, alt text, and class passthrough.

AttributeTypeDefaultDescription
srcstring''Source image URL. Mutually exclusive with disk + path.
diskstring|nullnullStorage disk name. Requires path.
pathstring|nullnullFile path on the disk. Requires disk.
presetstring|nullnullNamed preset from config to compose before overrides.
widthsarray|string|nullnullSrcset width candidates (array or comma-separated string). Mutually exclusive with dprs.
dprsarray|string|nullnullSrcset DPR candidates (array or comma-separated string). Mutually exclusive with widths.
sizesstring|nullnullThe sizes attribute for the <img>.
placeholderboolfalseWhen true, src is a tiny blurred webp; the full image is reachable through the srcset.
altstring|nullnullAlt text for the <img>.
loadingstring'lazy'Loading strategy (lazy or eager).
blade
<x-imgproxy-img
    src="https://example.com/image.jpg"
    :widths="[320, 640, 1280]"
    sizes="(min-width: 1024px) 50vw, 100vw"
    preset="thumb"
    placeholder
    alt="A photo"
    class="rounded shadow"
/>

The <x-imgproxy-picture> Component

Renders a <picture> with one <source> per format and a fallback <img>. Every format except the last becomes a <source>; the last is the fallback image.

Inherits all <x-imgproxy-img> attributes, plus:

AttributeTypeDefaultDescription
formatsarray|string|null['avif', 'webp', 'jpg']Output formats. The last is the fallback <img>.
blade
<x-imgproxy-picture
    src="https://example.com/image.jpg"
    :widths="[640, 1280]"
    :formats="['avif', 'webp', 'jpg']"
    sizes="100vw"
    alt="A photo"
/>

Storage Macro

Registered on Illuminate\Filesystem\FilesystemAdapter by the service provider:

php
FilesystemAdapter::macro('imgproxy', function (string $path, int|DateTimeInterface|null $expiration = null): Builder

Public disks yield url(); private disks (those providing temporary URLs without explicit public visibility) yield a pre-signed temporaryUrl().

php
use Illuminate\Support\Facades\Storage;

// Public disk
Storage::disk('public')->imgproxy('images/photo.jpg')->width(800)->url();

// Private disk with 1-hour expiry
Storage::disk('s3')->imgproxy('products/image.jpg', 3600)->resize(ResizeType::Fill, 800, 600)->url();

Configuration

Published config file: config/laravel-imgproxy.php.

Instances

Each instance points at one imgproxy server. The default instance reads from environment variables.

php
'instances' => [
    'default' => [
        'url' => env('IMGPROXY_URL'),             // Base URL, no trailing slash
        'key' => env('IMGPROXY_KEY'),             // Hex-encoded HMAC key, or null for unsigned URLs
        'salt' => env('IMGPROXY_SALT'),           // Hex-encoded HMAC salt
        'signature_size' => null,                 // Bytes to keep (1–32), null for full 32
        'encoding' => 'base64',                   // "base64" (URL-safe, default) or "plain" (percent-encoded)
    ],
],

Presets

Named option sets shared across instances. Keys match the fluent method names; only single-value options are supported.

php
'presets' => [
    'thumb' => [
        'resize' => 'fill',
        'width' => 300,
        'height' => 300,
    ],
],

Artisan Commands

imgproxy:key

Generates a fresh 32-byte hex key and salt pair for URL signing. Prints environment lines for you to copy into .env.

bash
php artisan imgproxy:key

Generated a new imgproxy key and salt pair.

IMGPROXY_KEY=...
IMGPROXY_SALT=...

The command never writes to .env itself.

imgproxy:health

Checks an instance's /health endpoint and exits non-zero when the instance is unreachable, unhealthy, or not configured.

bash
php artisan imgproxy:health              # default instance
php artisan imgproxy:health --instance=staging

Released under the MIT License.