Oihana PHP

ImageTrait uses trait:short

Provides image helpers built on top of Imagick: dimension inspection, on-the-fly resizing and shadow effects, and PSR-7 responses that stream an image file or an in-memory Imagick blob.

Transform and header behavior is driven by the $options arrays, keyed by the ResizeOption, ImagickResponseOption and FileResponseOption enums. The images root path can be centralized through self::initializeImagePath().

Tags
author

Marc Alcaraz (ekameleon)

since
1.0.0

Table of Contents

Constants

DEFAULT_COMPRESSION  : int = \Imagick::COMPRESSION_JPEG
The default Imagick compression of the output image.
DEFAULT_FORMAT  : string = 'jpg'
The default output image format.
DEFAULT_MAX_HEIGHT  : int = 1200
The default maximum height used by {@see self::resize()}.
DEFAULT_MAX_WIDTH  : int = 1920
The default maximum width used by {@see self::resize()}.
DEFAULT_QUALITY  : int = 70
The default Imagick compression quality (0-100).
IMAGE_PATH  : string = 'imagePath'
The key used to initialize the images root path from an array.

Properties

$imagePath  : string
The root path where the images are stored on the server.

Methods

fail()  : ResponseInterface|null
Generates a structured error response with an HTTP status code and optional detailed messages.
getImageDimensions()  : array<string|int, mixed>|null
Returns the dimensions (width and height) of an image.
getImageHeight()  : int
Returns the height of an image.
getImagePath()  : string
Returns the root path where the images are stored on the server.
getImageWidth()  : int
Returns the width of an image.
imageResponse()  : ResponseInterface
Streams an image file as a PSR-7 response.
imagickResponse()  : ResponseInterface
Returns an image response, applying optional Imagick transforms beforehand.
initializeImagePath()  : static
Initializes the images root path.
resize()  : string|Imagick|null
Resizes an image, clamping it to the configured maximum dimensions and optionally fitting it to an explicit width and/or height.
response()  : ResponseInterface
Return a response in the format accepted by the client : JSON by default or CBOR.
shadow()  : string|Imagick|null
Applies a drop shadow over an image.
status()  : ResponseInterface|null
Outputs a generic HTTP status message in a JSON response.
success()  : mixed
Outputs a success message with optional JSON metadata.
successWithNewBody()  : mixed
Same as {@see self::success()} but guarantees a fresh response body stream before writing the envelope.
withFreshBody()  : ResponseInterface|null
Returns the same response with a fresh, empty body stream.

Constants

DEFAULT_COMPRESSION

The default Imagick compression of the output image.

public int DEFAULT_COMPRESSION = \Imagick::COMPRESSION_JPEG

DEFAULT_FORMAT

The default output image format.

public string DEFAULT_FORMAT = 'jpg'

DEFAULT_MAX_HEIGHT

The default maximum height used by {@see self::resize()}.

public int DEFAULT_MAX_HEIGHT = 1200

DEFAULT_MAX_WIDTH

The default maximum width used by {@see self::resize()}.

public int DEFAULT_MAX_WIDTH = 1920

DEFAULT_QUALITY

The default Imagick compression quality (0-100).

public int DEFAULT_QUALITY = 70

IMAGE_PATH

The key used to initialize the images root path from an array.

public string IMAGE_PATH = 'imagePath'

Properties

$imagePath

The root path where the images are stored on the server.

public string $imagePath = ''

Methods

fail()

Generates a structured error response with an HTTP status code and optional detailed messages.

public fail(ServerRequestInterface|null $request, ResponseInterface|null $response[, int|string|null $code = 400 ][, string|null $details = null ][, array<string|int, mixed> $options = [] ][, string|null $accept = null ]) : ResponseInterface|null

Automatically logs the error if logging is enabled.

The status is always one a response can carry : a code between 100 and 599 is kept as it is — a redirection included, since an API may answer 301 to retire a version — and anything else answers 500. A PSR-7 response refuses a status outside that range, so a code of 0 or 600 made the response throw instead of carrying the error. Two of those come easily : HttpStatusCode::DEFAULT is 0 and BUSY is 600, and a code that is no number at all — the SQLSTATE of a database failure, 'HY000' — reads as 0 once cast to an integer.

Parameters
$request : ServerRequestInterface|null

Optional PSR-7 Request object.

$response : ResponseInterface|null

The PSR-7 Response object.

$code : int|string|null = 400

The HTTP status code (default: 400). Anything but a status of 100 to 599 answers 500.

$details : string|null = null

Optional detailed error message to override default description.

$options : array<string|int, mixed> = []

Optional array of additional data to include (e.g., errors).

$accept : string|null = null

The header accepted by the client : 'application/cbor' or by default 'application/json'

Tags
example
return $this->fail(
    $response,
    406,
    'fields validation failed',
    [
        'firstName' => 'firstName is required',
        'lastName'  => 'lastName must be a string'
    ]
);
Return values
ResponseInterface|null —

Returns a PSR-7 Response object with JSON content or null if $response is not provided.

getImageDimensions()

Returns the dimensions (width and height) of an image.

public getImageDimensions(Imagick|string $image) : array<string|int, mixed>|null
Parameters
$image : Imagick|string

The Imagick instance or the path of the image file.

Tags
throws
ImagickException

If the image cannot be read or decoded by Imagick.

Return values
array<string|int, mixed>|null —

An associative array with width and height keys.

getImageHeight()

Returns the height of an image.

public getImageHeight(Imagick|string $image) : int
Parameters
$image : Imagick|string

The Imagick instance or the path of the image file.

Tags
throws
ImagickException

If the image cannot be read or decoded by Imagick.

Return values
int —

The image height in pixels.

getImagePath()

Returns the root path where the images are stored on the server.

public getImagePath() : string
Return values
string —

The images root path.

getImageWidth()

Returns the width of an image.

public getImageWidth(Imagick|string $image) : int
Parameters
$image : Imagick|string

The Imagick instance or the path of the image file.

Tags
throws
ImagickException

If the image cannot be read or decoded by Imagick.

Return values
int —

The image width in pixels.

imageResponse()

Streams an image file as a PSR-7 response.

public imageResponse(ServerRequestInterface|null $request, ResponseInterface $response, string $file[, array<string|int, mixed> $options = [] ]) : ResponseInterface

The file is validated with assertFile() first; a missing or unreadable file is reported as a 500 response (see the catch below). Optional content headers are toggled via $options, keyed by FileResponseOption.

Parameters
$request : ServerRequestInterface|null

Optional PSR-7 Request object (used to build the failure response).

$response : ResponseInterface

The PSR-7 Response object to write the image into.

$file : string

Absolute path of the image file to send.

$options : array<string|int, mixed> = []

Optional header switches (see FileResponseOption).

Return values
ResponseInterface —

The response carrying the image body, or a 500 failure response on error.

imagickResponse()

Returns an image response, applying optional Imagick transforms beforehand.

public imagickResponse(ResponseInterface $response, string|Imagick $image[, array<string|int, mixed> $options = [] ]) : ResponseInterface
Parameters
$response : ResponseInterface

The PSR-7 Response object to write the image into.

$image : string|Imagick

The Imagick instance or the path of the image file.

$options : array<string|int, mixed> = []

Optional transform/header switches (see ImagickResponseOption and FileResponseOption).

Return values
ResponseInterface —

The response carrying the transformed image, or a 500 failure response on error.

initializeImagePath()

Initializes the images root path.

public initializeImagePath([string|array<string|int, mixed> $init = [] ]) : static
Parameters
$init : string|array<string|int, mixed> = []

Either the path string directly, or an array carrying it under the self::IMAGE_PATH key.

Return values
static —

Returns the current instance for method chaining.

resize()

Resizes an image, clamping it to the configured maximum dimensions and optionally fitting it to an explicit width and/or height.

public resize(Imagick|string|null $image[, int|null $w = null ][, int|null $h = null ][, array<string|int, mixed> $options = [] ]) : string|Imagick|null

When only one of $w/$h is given, the other is derived from aspectFit() so the aspect ratio is preserved. A null input is returned untouched.

Ex: ../image?resize=true&w=50&h=50

Parameters
$image : Imagick|string|null

The url of the image file or the Imagick object reference to transform.

$w : int|null = null

Optional explicit target width.

$h : int|null = null

Optional explicit target height.

$options : array<string|int, mixed> = []

Optional overrides (see ResizeOption).

Tags
throws
ImagickException

If the image cannot be read, decoded or resized by Imagick.

Return values
string|Imagick|null —

The transformed Imagick instance, or the original input when no transform applies.

response()

Return a response in the format accepted by the client : JSON by default or CBOR.

public response(ResponseInterface $response[, mixed $data = null ][, int $status = 200 ][, string|null $accept = null ]) : ResponseInterface

Checks the Accept header in the request to determine the preferred format.

Parameters
$response : ResponseInterface

PSR-7 Response object to write to.

$data : mixed = null

Data to send in the response.

$status : int = 200

HTTP status code (default: 200).

$accept : string|null = null

The header accepted by the client : 'application/cbor' or by default 'application/json'

Tags
see
FileMimeType::JSON
FileMimeType::CBOR
FileMimeType::CBOR_SEQ
Return values
ResponseInterface —

The response encoded as CBOR or JSON according to the negotiated format.

shadow()

Applies a drop shadow over an image.

public shadow(Imagick|string|null $image[, string|null $value = null ]) : string|Imagick|null

The shadow is described by a comma-separated opacity,sigma,x,y string; any other shape (or a null image) leaves the input unchanged.

Ex: ../image?shadow=true Ex: ../image?shadow=60,4,10,20

Parameters
$image : Imagick|string|null

The url of the image file or the Imagick object reference to transform.

$value : string|null = null

The shadow definition: opacity,sigma,x,y.

Tags
throws
ImagickException

If the image cannot be read, decoded or composited by Imagick.

Return values
string|Imagick|null —

The composited Imagick instance, or the original input when no shadow applies.

status()

Outputs a generic HTTP status message in a JSON response.

public status(ServerRequestInterface|null $request, ResponseInterface|null $response[, mixed $message = Char::EMPTY ][, int|string|null $code = 200 ][, array<string|int, mixed>|null $options = null ][, string|null $accept = null ]) : ResponseInterface|null
Parameters
$request : ServerRequestInterface|null

Optional PSR-7 Request object.

$response : ResponseInterface|null

PSR-7 Response object to send output.

$message : mixed = Char::EMPTY

The message content.

$code : int|string|null = 200

The HTTP status code (default: 200).

$options : array<string|int, mixed>|null = null

Optional array of additional output properties.

$accept : string|null = null

The header accepted by the client : 'application/cbor' or by default 'application/json'

Tags
example
return $this->status($response, 'bad request', 405);
Return values
ResponseInterface|null —

Returns a PSR-7 Response object with JSON content or null if $response is not provided.

success()

Outputs a success message with optional JSON metadata.

public success(ServerRequestInterface|null $request, ResponseInterface|null $response[, mixed $data = null ][, array<string|int, mixed>|null $init = null ][, string|null $accept = null ]) : mixed

If $response is null, returns the $data directly. Supports optional initialization properties like count, limit, offset, owner, URL, status, total, position, options.

Parameters
$request : ServerRequestInterface|null

Optional PSR-7 Request object.

$response : ResponseInterface|null

Optional PSR-7 Response object.

$data : mixed = null

The main payload or data to return.

$init : array<string|int, mixed>|null = null

Optional associative array with keys:

  • count (int): Number of elements
  • limit (int): Pagination limit
  • offset (int): Pagination offset
  • params (array): Parameters for getCurrentPath()
  • status (int): HTTP status code
  • total (int): Total elements
  • url (string): URL to include in response
  • owner (array|object): Owner reference
  • options (array): Additional properties
  • position (int): Optional position in list
$accept : string|null = null

The header accepted by the client : 'application/cbor' or by default 'application/json'

Tags
example
return $this->success(
    $request,
    $response,
    $data,
    [Output::COUNT => count($data), Output::PARAMS => $request->getQueryParams()]
);
Return values
mixed —

Returns a PSR-7 Response object with JSON if $response is provided, otherwise returns $data directly.

successWithNewBody()

Same as {@see self::success()} but guarantees a fresh response body stream before writing the envelope.

public successWithNewBody(ServerRequestInterface|null $request, ResponseInterface|null $response[, mixed $data = null ][, array<string|int, mixed>|null $init = null ][, string|null $accept = null ]) : mixed

Use this only when an upstream actor (typically a sub-controller called from the current controller method) may have already written into the shared PSR-7 body stream. Calling the plain success() in that case would concatenate two JSON envelopes — invalid JSON for any strict parser (NextJS RSC, modern fetch, etc.).

Implementation: swaps the response body for an empty stream via self::withFreshBody(), then delegates to success(). Whatever was previously written is discarded; the resulting body contains exactly one envelope.

Parameters
$request : ServerRequestInterface|null

Optional PSR-7 Request object.

$response : ResponseInterface|null

Optional PSR-7 Response object.

$data : mixed = null

The main payload or data to return.

$init : array<string|int, mixed>|null = null

Same keys as success().

$accept : string|null = null

The header accepted by the client.

Tags
example
// POST /users where dispatchAutoInvitation() writes into the shared body
public function post( ?Request $request , ?Response $response , array $args , array $init ) :mixed
{
    $result = parent::post( $request , $response , $args , $init ) ;
    $this->dispatchAutoInvitation( $request , $response , $userKey ) ;

    return $this->successWithNewBody
    (
        $request ,
        $result  ,
        $this->refetchHydratedUser( $userKey )
    ) ;
}
see
success()

Plain variant when the body has not been touched.

Return values
mixed —

Same return contract as success().

withFreshBody()

Returns the same response with a fresh, empty body stream.

public withFreshBody(ResponseInterface|null $response) : ResponseInterface|null

Use to discard whatever an upstream actor (sub-controller, middleware) may have already written, then chain into any other response helper.

Parameters
$response : ResponseInterface|null

Optional PSR-7 Response object.

Tags
example
return $this->fail( $request , $this->withFreshBody( $response ) , 502 , 'zitadel_sync_failed' ) ;
Return values
ResponseInterface|null —

The same response with a fresh empty body, or null if $response was null.

On this page

Search results