Nette Documentation Preview

syntax
Image Functions
***************

.[perex]
The [api:Nette\Utils\Image] class simplifies image manipulation, such as resizing, cropping, sharpening, drawing, or merging multiple images.


PHP has an extensive set of functions for manipulating images. But the API is not very nice. It wouldn't be a Nette Framework to come up with a sexy API.

Installation:

```shell
composer require nette/utils
```

Following examples assume the following class alias is defined:

```php
use Nette\Utils\Image;
```


Creating an Image
=================

We'll create a new true color image, for example with dimensions of 100×200:

```php
$image = Image::fromBlank(100, 200);
```

Optionally, you can specify a background color (default is black):

```php
$image = Image::fromBlank(100, 200, Image::rgb(125, 0, 0));
```

Or we load the image from a file:

```php
$image = Image::fromFile('nette.jpg');
```

Supported formats are JPEG, PNG, GIF, WebP, AVIF and BMP, but your version of PHP must also support them (check the `phpinfo()`, section GD). Animations are not supported.

Need to detect the image format when loading? The method returns format in the second parameter:

```php
$image = Image::fromFile('nette.jpg', $type);
// $type is Image::JPEG, Image::PNG, Image::GIF, Image::WEBP, Image::AVIF or Image::BMP
```

Only the detection without loading the image is done by `Image::detectTypeFromFile()` (as of nette/utils 3.2).


Save the Image
==============

The image can be saved to a file:

```php
$image->save('resampled.jpg');
```

We can specify compression quality in the range 0..100 for JPEG (default 85), WEBP (default 80) and AVIF (default 30) and 0..9 for PNG (default 9):

```php
$image->save('resampled.jpg', 80); // JPEG, quality 80%
```

If the format is not obvious from the file extension, it can be specified by one of the constants `Image::JPEG`, `Image::PNG`, `Image::GIF`, `Image::WEBP`, `Image::AVIF`, and `Image::BMP`:

```php
$image->save('resampled.tmp', null, Image::JPEG);
```

The image can be written to a variable instead of to disk:

```php
$data = $image->toString(Image::JPEG, 80); // JPEG, quality 80%
```

or send directly to the browser with the appropriate HTTP header `Content-Type`:

```php
// sends header Content-Type: image/png
$image->send(Image::PNG);
```


Image Resize
============

A common operation is to resize an image. The current dimensions are returned by methods `getWidth()` and `getHeight()`.

The method `resize()` is used for resizing. This is example of proportional size change so that it does not exceed 500×300 pixels (either the width will be exactly 500px or the height will be exactly 300px, one of dimensions is calculated to maintain the aspect ratio):

```php
$image->resize(500, 300);
```

It's possible to set only one dimension and the second one will be calculated:

```php
$image->resize(500, null); // width 500px, height auto

$image->resize(null, 300); // width auto, height 300px
```

Any dimension can be specified in percentages:

```php
$image->resize('75%', 300); // 75 % × 300px
```

The behavior of the `resize` function could be affected with following flags:

|---------------------------------------------------------------------------------------
| Flag                   | Description
|---------------------------------------------------------------------------------------
| `Image::FIT` (default) | resulting dimensions will be less or equal as specified
| `Image::FILL`          | fills the target area and possibly extends it in one direction
| `Image::EXACT`         | fills the whole area and cuts what exceeds
| `Image::SHRINK_ONLY`   | just scales down (does not extend a small image)
| `Image::STRETCH`       | does not keep the aspect ratio


The flags are passed as the third argument of the function:

```php
$image->resize(500, 300, Image::STRETCH);
```

Flags can be combined:

```php
$image->resize(500, 300, Image::SHRINK_ONLY | Image::STRETCH);
```

Images can be flipped vertically or horizontally by specifying one of the dimensions (or both) as a negative number:

```php
$flipped = $image->resize(null, '-100%'); // flip vertical

$flipped = $image->resize('-100%', '-100%'); // rotate by 180°

$flipped = $image->resize(-125, 500); // resize & flip horizontal
```

After reducing the image we can improve it by sharpening:

```php
$image->sharpen();
```


Cropping
========

The method `crop()` is used for cropping:

```php
$image->crop($left, $top, $width, $height);
```

As with `resize()`, all values can be specified in percentages. The percentages for `$left` and `$top` are calculated from the remaining space, similar to the CSS property `background-position`:

```php
$image->crop('100%', '50%', '80%', '80%');
```

[* crop.svg *]


The image can also be cropped automatically, eg cropped black edges:

```php
$image->cropAuto(IMG_CROP_BLACK);
```

Method `cropAuto()` is an object encapsulation of the `imagecropauto()` function, see [its documentation|https://www.php.net/manual/en/function.imagecropauto] for more information.


Drawing and Editing
===================

You can draw, you can write, you can use all PHP functions for working with images, such as [imagefilledellipse()|https://www.php.net/manual/en/function.imagefilledellipse.php], but using object style:

```php
$image->filledEllipse($cx, $cy, $width, $height, Image::rgb(255, 0, 0, 63));
```

See [#Overview of Methods].


Merge Multiple Images
=====================

You can easily place another image into the image:

```php
$logo = Image::fromFile('logo.png');
$blank = Image::fromBlank(320, 240, Image::rgb(52, 132, 210));

// coordinates can be set also in percentage
$blank->place($logo, '80%', '80%'); // near the right bottom corner
```

When pasting, the alpha channel is respected, in addition, we can influence the transparency of the inserted image (we will create a so-called watermark):

```php
$blank->place($image, '80%', '80%', 25); // transparency is 25 %
```

Such API is really a pleasure to use, isn't it?


Overview of Methods
===================


static fromBlank(int $width, int $height, ?array $color=null): Image .[method]
------------------------------------------------------------------------------
Creates a new true color image of the given dimensions. The default color is black.


static fromFile(string $file, int &$detectedFormat=null): Image .[method]
-------------------------------------------------------------------------
Reads an image from a file and returns its type in `$detectedFormat`. The supported types are `Image::JPEG`, `Image::PNG`, `Image::GIF`, `Image::WEBP`, `Image::AVIF` and `Image::BMP`.


static fromString(string $s, int &$detectedFormat=null): Image .[method]
------------------------------------------------------------------------
Reads an image from a string and returns its type in `$detectedFormat`. The supported types are `Image::JPEG`, `Image::PNG`, `Image::GIF`, `Image::WEBP`, `Image::AVIF`, and `Image::BMP`.


static rgb(int $red, int $green, int $blue, int $transparency=0): array .[method]
---------------------------------------------------------------------------------
Creates a color that can be used in other methods, such as `ellipse()`, `fill()`, and so on.


static typeToExtension(int $type): string .[method]{data-version:v3.1.1}
------------------------------------------------------------------------
Returns the file extension for the given `Image::XXX` constant.


static typeToMimeType(int $type): string .[method]{data-version:v3.1.1}
-----------------------------------------------------------------------
Returns the mime type for the given `Image::XXX` constant.


static extensionToType(string $extension): int .[method]{data-version:v3.2.8}
-----------------------------------------------------------------------------
Returns the image type as a constant `Image::XXX` according to the file extension.


static detectTypeFromFile(string $file, int &$width=null, int &$height=null): ?int .[method]{data-version:v3.2.0}
-----------------------------------------------------------------------------------------------------------------
Returns the type of image file as `Image::XXX` constant and in the `$width` and `$height` parameters also its dimensions.


static detectTypeFromString(string $s, int &$width=null, int &$height=null): ?int .[method]{data-version:v3.2.0}
----------------------------------------------------------------------------------------------------------------
Returns the type of image from string as `Image::XXX` constant and in the `$width` and `$height` parameters also its dimensions.


affine(array $affine, ?array $clip=null): Image .[method]
---------------------------------------------------------
Return an image containing the affine transformed src image, using an optional clipping area. ([more|https://www.php.net/manual/en/function.imageaffine]).


affineMatrixConcat(array $m1, array $m2): array .[method]
---------------------------------------------------------
Returns the concatenation of two affine transformation matrices, what is useful if multiple transformations should be applied to the same image in one go. ([more|https://www.php.net/manual/en/function.imageaffinematrixconcat])


affineMatrixGet(int $type, ?mixed $options=null): array .[method]
-----------------------------------------------------------------
Returns an affine transformation matrix. ([more|https://www.php.net/manual/en/function.imageaffinematrixget])


alphaBlending(bool $on): void .[method]
---------------------------------------
Allows for two different modes of drawing on truecolor images. In blending mode, the alpha channel component of the color supplied to all drawing function, such as `setPixel()` determines how much of the underlying color should be allowed to shine through. As a result, it automatically blends the existing color at that point with the drawing color, and stores the result in the image. The resulting pixel is opaque. In non-blending mode, the drawing color is copied literally with its alpha channel information, replacing the destination pixel. Blending mode is not available when drawing on palette images. ([more|https://www.php.net/manual/en/function.imagealphablending])


antialias(bool $on): void .[method]
-----------------------------------
Activate the fast drawing antialiased methods for lines and wired polygons. It does not support alpha components. It works using a direct blend operation. It works only with truecolor images.

Using antialiased primitives with transparent background color can end with some unexpected results. The blend method uses the background color as any other colors. The lack of alpha component support does not allow an alpha based antialiasing method. ([more|https://www.php.net/manual/en/function.imageantialias])


arc(int $x, int $y, int $w, int $h, int $start, int $end, int $color): void .[method]
-------------------------------------------------------------------------------------
Draws an arc of circle centered at the given coordinates. ([more|https://www.php.net/manual/en/function.imagearc])


char(int $font, int $x, int $y, string $char, int $color): void .[method]
-------------------------------------------------------------------------
Draws the first character of `$char` in the image with its upper-left at `$x`,`$y` (top left is 0, 0) with the color `$color`. ([more|https://www.php.net/manual/en/function.imagechar])


charUp(int $font, int $x, int $y, string $char, int $color): void .[method]
---------------------------------------------------------------------------
Draws the character `$char` vertically at the specified coordinate on the given image. ([more|https://www.php.net/manual/en/function.imagecharup])


colorAllocate(int $red, int $green, int $blue): int .[method]
-------------------------------------------------------------
Returns a color identifier representing the color composed of the given RGB components. It must be called to create each color that is to be used in the image. ([more|https://www.php.net/manual/en/function.imagecolorallocate])


colorAllocateAlpha(int $red, int $green, int $blue, int $alpha): int .[method]
------------------------------------------------------------------------------
Behaves identically to `colorAllocate()` with the addition of the transparency parameter `$alpha`. ([more|https://www.php.net/manual/en/function.imagecolorallocatealpha])


colorAt(int $x, int $y): int .[method]
--------------------------------------
Returns the index of the color of the pixel at the specified location in the image. If the image is a truecolor image, this function returns the RGB value of that pixel as integer. Use bitshifting and masking to access the distinct red, green and blue component values: ([more|https://www.php.net/manual/en/function.imagecolorat])


colorClosest(int $red, int $green, int $blue): int .[method]
------------------------------------------------------------
Returns the index of the color in the palette of the image which is "closest" to the specified RGB value. The "distance" between the desired color and each color in the palette is calculated as if the RGB values represented points in three-dimensional space. ([more|https://www.php.net/manual/en/function.imagecolorclosest])


colorClosestAlpha(int $red, int $green, int $blue, int $alpha): int .[method]
-----------------------------------------------------------------------------
Returns the index of the color in the palette of the image which is "closest" to the specified RGB value and `$alpha` level. ([more|https://www.php.net/manual/en/function.imagecolorclosestalpha])


colorClosestHWB(int $red, int $green, int $blue): int .[method]
---------------------------------------------------------------
Get the index of the color which has the hue, white and blackness nearest the given color. ([more|https://www.php.net/manual/en/function.imagecolorclosesthwb])


colorDeallocate(int $color): void .[method]
-------------------------------------------
De-allocates a color previously allocated with `colorAllocate()` or `colorAllocateAlpha()`. ([more|https://www.php.net/manual/en/function.imagecolordeallocate])


colorExact(int $red, int $green, int $blue): int .[method]
----------------------------------------------------------
Returns the index of the specified color in the palette of the image. ([more|https://www.php.net/manual/en/function.imagecolorexact])


colorExactAlpha(int $red, int $green, int $blue, int $alpha): int .[method]
---------------------------------------------------------------------------
Returns the index of the specified color+alpha in the palette of the image. ([more|https://www.php.net/manual/en/function.imagecolorexactalpha])


colorMatch(Image $image2): void .[method]
-----------------------------------------
Makes the colors of the palette version of an image more closely match the true color version. ([more|https://www.php.net/manual/en/function.imagecolormatch])


colorResolve(int $red, int $green, int $blue): int .[method]
------------------------------------------------------------
Returns a color index for a requested color, either the exact color or the closest possible alternative. ([more|https://www.php.net/manual/en/function.imagecolorresolve])


colorResolveAlpha(int $red, int $green, int $blue, int $alpha): int .[method]
-----------------------------------------------------------------------------
Returns a color index for a requested color, either the exact color or the closest possible alternative. ([more|https://www.php.net/manual/en/function.imagecolorresolvealpha])


colorSet(int $index, int $red, int $green, int $blue): void .[method]
---------------------------------------------------------------------
This sets the specified index in the palette to the specified color. ([more|https://www.php.net/manual/en/function.imagecolorset])


colorsForIndex(int $index): array .[method]
-------------------------------------------
Gets the color for a specified index. ([more|https://www.php.net/manual/en/function.imagecolorsforindex])


colorsTotal(): int .[method]
----------------------------
Returns the number of colors in an image palette. ([more|https://www.php.net/manual/en/function.imagecolorstotal])


colorTransparent(?int $color=null): int .[method]
-------------------------------------------------
Gets or sets the transparent color in the image. ([more|https://www.php.net/manual/en/function.imagecolortransparent])


convolution(array $matrix, float $div, float $offset): void .[method]
---------------------------------------------------------------------
Applies a convolution matrix on the image, using the given coefficient and offset. ([more|https://www.php.net/manual/en/function.imageconvolution])

.[note]
Requires *Bundled GD extension*, so it is not sure it will work everywhere.


copy(Image $src, int $dstX, int $dstY, int $srcX, int $srcY, int $srcW, int $srcH): void .[method]
--------------------------------------------------------------------------------------------------
Copies a part of `$src` onto image starting at the coordinates `$srcX`, `$srcY` with a width of `$srcW` and a height of `$srcH`. The portion defined will be copied onto the coordinates, `$dstX` and `$dstY`. ([more|https://www.php.net/manual/en/function.imagecopy])


copyMerge(Image $src, int $dstX, int $dstY, int $srcX, int $srcY, int $srcW, int $srcH, int $opacity): void .[method]
---------------------------------------------------------------------------------------------------------------------
Copies a part of `$src` onto image starting at the coordinates `$srcX`, `$srcY` with a width of `$srcW` and a height of `$srcH`. The portion defined will be copied onto the coordinates, `$dstX` and `$dstY`. ([more|https://www.php.net/manual/en/function.imagecopymerge])


copyMergeGray(Image $src, int $dstX, int $dstY, int $srcX, int $srcY, int $srcW, int $srcH, int $opacity): void .[method]
-------------------------------------------------------------------------------------------------------------------------
Copies a part of `$src` onto image starting at the coordinates `$srcX`, `$srcY` with a width of `$srcW` and a height of `$srcH`. The portion defined will be copied onto the coordinates, `$dstX` and `$dstY`.

This function is identical to `copyMerge()` except that when merging it preserves the hue of the source by converting the destination pixels to gray scale before the copy operation. ([more|https://www.php.net/manual/en/function.imagecopymergegray])


copyResampled(Image $src, int $dstX, int $dstY, int $srcX, int $srcY, int $dstW, int $dstH, int $srcW, int $srcH): void .[method]
---------------------------------------------------------------------------------------------------------------------------------
Copies a rectangular portion of one image to another image, smoothly interpolating pixel values so that, in particular, reducing the size of an image still retains a great deal of clarity.

In other words, `copyResampled()` will take a rectangular area from `$src` of width `$srcW` and height `$srcH` at position (`$srcX`,`$srcY`) and place it in a rectangular area of image of width `$dstW` and height `$dstH` at position (`$dstX`,`$dstY`).

If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed. The coordinates refer to the upper left corner. This function can be used to copy regions within the same image but if the regions overlap the results will be unpredictable. ([more|https://www.php.net/manual/en/function.imagecopyresampled])


copyResized(Image $src, int $dstX, int $dstY, int $srcX, int $srcY, int $dstW, int $dstH, int $srcW, int $srcH): void .[method]
-------------------------------------------------------------------------------------------------------------------------------
Copies a rectangular portion of one image to another image. In other words, `copyResized()` will take a rectangular area from `$src` of width `$srcW` and height `$srcH` at position (`$srcX`,`$srcY`) and place it in a rectangular area of image of width `$dstW` and height `$dstH` at position (`$dstX`,`$dstY`).

If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed. The coordinates refer to the upper left corner. This function can be used to copy regions within the same image but if the regions overlap the results will be unpredictable. ([more|https://www.php.net/manual/en/function.imagecopyresized])


crop(int|string $left, int|string $top, int|string $width, int|string $height): Image .[method]
-----------------------------------------------------------------------------------------------
Crops an image to the given rectangular area. Dimensions can be passed as integers in pixels or strings in percent (i.e. `'50%'`).


cropAuto(int $mode=-1, float $threshold=.5, int $color=-1): Image .[method]
---------------------------------------------------------------------------
Automatically crops an image according to the given `$mode`. ([more|https://www.php.net/manual/en/function.imagecropauto])


ellipse(int $cx, int $cy, int $w, int $h, int $color): void .[method]
---------------------------------------------------------------------
Draws an ellipse centered at the specified coordinates. ([more|https://www.php.net/manual/en/function.imageellipse])


fill(int $x, int $y, int $color): void .[method]
------------------------------------------------
Performs a flood fill starting at the given coordinate (top left is 0, 0) with the given `$color` in the image. ([more|https://www.php.net/manual/en/function.imagefill])


filledArc(int $cx, int $cy, int $w, int $h, int $s, int $e, int $color, int $style): void .[method]
---------------------------------------------------------------------------------------------------
Draws a partial arc centered at the specified coordinate in the image. ([more|https://www.php.net/manual/en/function.imagefilledarc])


filledEllipse(int $cx, int $cy, int $w, int $h, int $color): void .[method]
---------------------------------------------------------------------------
Draws an ellipse centered at the specified coordinate in the image. ([more|https://www.php.net/manual/en/function.imagefilledellipse])


filledPolygon(array $points, int $numPoints, int $color): void .[method]
------------------------------------------------------------------------
Creates a filled polygon in the $image. ([more|https://www.php.net/manual/en/function.imagefilledpolygon])


filledRectangle(int $x1, int $y1, int $x2, int $y2, int $color): void .[method]
-------------------------------------------------------------------------------
Creates a rectangle filled with `$color` in the image starting at point 1 and ending at point 2. 0, 0 is the top left corner of the image. ([more|https://www.php.net/manual/en/function.imagefilledrectangle])


fillToBorder(int $x, int $y, int $border, int $color): void .[method]
---------------------------------------------------------------------
Performs a flood fill whose border color is defined by `$border`. The starting point for the fill is `$x`, `$y` (top left is 0, 0) and the region is filled with color `$color`. ([more|https://www.php.net/manual/en/function.imagefilltoborder])


filter(int $filtertype, int ...$args): void .[method]
-----------------------------------------------------
Applies the given filter `$filtertype` on the image. ([more|https://www.php.net/manual/en/function.imagefilter])


flip(int $mode): void .[method]
-------------------------------
Flips the image using the given `$mode`. ([more|https://www.php.net/manual/en/function.imageflip])


ftText(int $size, int $angle, int $x, int $y, int $col, string $fontFile, string $text, ?array $extrainfo=null): array .[method]
--------------------------------------------------------------------------------------------------------------------------------
Write text to the image using fonts using FreeType 2. ([more|https://www.php.net/manual/en/function.imagefttext])


gammaCorrect(float $inputgamma, float $outputgamma): void .[method]
-------------------------------------------------------------------
Applies gamma correction to the image given an input and an output gamma. ([more|https://www.php.net/manual/en/function.imagegammacorrect])


getClip(): array .[method]{data-version:PHP 7.2}
------------------------------------------------
Retrieves the current clipping rectangle, i.e. the area beyond which no pixels will be drawn. ([more|https://www.php.net/manual/en/function.imagegetclip])


getHeight(): int .[method]
--------------------------
Returns the height of the image.


getImageResource(): resource|GdImage .[method]
----------------------------------------------
Returns the original resource.


getWidth(): int .[method]
-------------------------
Returns the width of the image.


interlace(?int $interlace=null): int .[method]
----------------------------------------------
Turns the interlace bit on or off. If the interlace bit is set and the image is used as a JPEG image, the image is created as a progressive JPEG. ([more|https://www.php.net/manual/en/function.imageinterlace])


isTrueColor(): bool .[method]
-----------------------------
Finds whether the image is a truecolor. ([more|https://www.php.net/manual/en/function.imageistruecolor])


layerEffect(int $effect): void .[method]
----------------------------------------
Set the alpha blending flag to use layering effects. ([more|https://www.php.net/manual/en/function.imagelayereffect])


line(int $x1, int $y1, int $x2, int $y2, int $color): void .[method]
--------------------------------------------------------------------
Draws a line between the two given points. ([more|https://www.php.net/manual/en/function.imageline])


openPolygon(array $points, int $numPoints, int $color): void .[method]{data-version:PHP 7.2}
--------------------------------------------------------------------------------------------
Draws an open polygon on the image. Contrary to `polygon()`, no line is drawn between the last and the first point. ([more|https://www.php.net/manual/en/function.imageopenpolygon])


paletteCopy(Image $source): void .[method]
------------------------------------------
Copies the palette from the `$source` to the image. ([more|https://www.php.net/manual/en/function.imagepalettecopy])


paletteToTrueColor(): void .[method]
------------------------------------
Converts a palette based image, created by functions like `create()` to a true color image, like `createtruecolor()`. ([more|https://www.php.net/manual/en/function.imagepalettetotruecolor])


place(Image $image, int|string $left=0, int|string $top=0, int $opacity=100): Image .[method]
---------------------------------------------------------------------------------------------
Copies `$image` to the image at the coordinates `$left` and `$top`. Coordinates can be passed as integers in pixels or strings in percent (i.e. `'50%'`).


polygon(array $points, int $numPoints, int $color): void .[method]
------------------------------------------------------------------
Creates a polygon in the image. ([more|https://www.php.net/manual/en/function.imagepolygon])


rectangle(int $x1, int $y1, int $x2, int $y2, int $col): void .[method]
-----------------------------------------------------------------------
Creates a rectangle starting at the specified coordinates. ([more|https://www.php.net/manual/en/function.imagerectangle])


resize(int|string $width, int|string $height, int $flags=Image::FIT): Image .[method]
-------------------------------------------------------------------------------------
Scales an image, see [more info|#Image Resize]. Dimensions can be passed as integers in pixels or strings in percent (i.e. `'50%'`).


resolution(?int $resX=null, ?int $resY=null): mixed .[method]{data-version:PHP 7.2}
-----------------------------------------------------------------------------------
Allows to set and get the resolution of an image in DPI (dots per inch). If none of the optional parameters is given, the current resolution is returned as indexed array. If only `$resX` is given, the horizontal and vertical resolution are set to this value. If both optional parameters are given, the horizontal and vertical resolution are set to these values, respectively.

The resolution is only used as meta information when images are read from and written to formats supporting this kind of information (curently PNG and JPEG). It does not affect any drawing operations. The default resolution for new images is 96 DPI. ([more|https://www.php.net/manual/en/function.imageresolution])


rotate(float $angle, int $backgroundColor): Image .[method]
-----------------------------------------------------------
Rotates the image using the given `$angle` in degrees. The center of rotation is the center of the image, and the rotated image may have different dimensions than the original image. ([more|https://www.php.net/manual/en/function.imagerotate])

.[note]
Requires *Bundled GD extension*, so it is not sure it will work everywhere.


save(string $file, ?int $quality=null, ?int $type=null): void .[method]
-----------------------------------------------------------------------
Saves an image to a file.

The compression quality is in the range 0..100 for JPEG (default 85), WEBP (default 80) and AVIF (default 30) and 0..9 for PNG (default 9). If the type is not obvious from the file extension, you can specify it using one of the constants `Image::JPEG`, `Image::PNG`, `Image::GIF`, `Image::WEBP`, `Image::AVIF`, and `Image::BMP`.


saveAlpha(bool $saveflag): void .[method]
-----------------------------------------
Sets the flag which determines whether to retain full alpha channel information (as opposed to single-color transparency) when saving PNG images.

Alphablending has to be disabled (`alphaBlending(false)`) to retain the alpha-channel in the first place. ([more|https://www.php.net/manual/en/function.imagesavealpha])


scale(int $newWidth, int $newHeight=-1, int $mode=IMG_BILINEAR_FIXED): Image .[method]
--------------------------------------------------------------------------------------
Scales an image using the given interpolation algorithm. ([more|https://www.php.net/manual/en/function.imagescale])


send(int $type=Image::JPEG, ?int $quality=null): void .[method]
---------------------------------------------------------------
Outputs an image to the browser.

The compression quality is in the range 0..100 for JPEG (default 85), WEBP (default 80) and AVIF (default 30) and 0..9 for PNG (default 9). Type is one of the constants `Image::JPEG`, `Image::PNG`, `Image::GIF`, `Image::WEBP`, `Image::AVIF` and `Image::BMP`.


setBrush(Image $brush): void .[method]
--------------------------------------
Sets the brush image to be used by all line drawing functions (such as `line()` and `polygon()`) when drawing with the special colors IMG_COLOR_BRUSHED or IMG_COLOR_STYLEDBRUSHED. ([more|https://www.php.net/manual/en/function.imagesetbrush])


setClip(int $x1, int $y1, int $x2, int $y2): void .[method]{data-version:PHP 7.2}
---------------------------------------------------------------------------------
Sets the current clipping rectangle, i.e. the area beyond which no pixels will be drawn. ([more|https://www.php.net/manual/en/function.imagesetclip])


setInterpolation(int $method=IMG_BILINEAR_FIXED): void .[method]
----------------------------------------------------------------
Sets the interpolation method which affects methods `rotate()` and `affine()`. ([more|https://www.php.net/manual/en/function.imagesetinterpolation])


setPixel(int $x, int $y, int $color): void .[method]
----------------------------------------------------
Draws a pixel at the specified coordinate. ([more|https://www.php.net/manual/en/function.imagesetpixel])


setStyle(array $style): void .[method]
--------------------------------------
Sets the style to be used by all line drawing functions (such as `line()` and `polygon()`) when drawing with the special color IMG_COLOR_STYLED or lines of images with color IMG_COLOR_STYLEDBRUSHED. ([more|https://www.php.net/manual/en/function.imagesetstyle])


setThickness(int $thickness): void .[method]
--------------------------------------------
Sets the thickness of the lines drawn when drawing rectangles, polygons, arcs etc. to `$thickness` pixels. ([more|https://www.php.net/manual/en/function.imagesetthickness])


setTile(Image $tile): void .[method]
------------------------------------
Sets the tile image to be used by all region filling functions (such as `fill()` and `filledPolygon()`) when filling with the special color IMG_COLOR_TILED.

A tile is an image used to fill an area with a repeated pattern. Any image can be used as a tile, and by setting the transparent color index of the tile image with `colorTransparent()`, a tile allows certain parts of the underlying area to shine through can be created. ([more|https://www.php.net/manual/en/function.imagesettile])


sharpen(): Image .[method]
--------------------------
Sharpens image a little bit.

.[note]
Requires *Bundled GD extension*, so it is not sure it will work everywhere.


string(int $font, int $x, int $y, string $str, int $col): void .[method]
------------------------------------------------------------------------
Draws a string at the given coordinates. ([more|https://www.php.net/manual/en/function.imagestring])


stringUp(int $font, int $x, int $y, string $s, int $col): void .[method]
------------------------------------------------------------------------
Draws a string vertically at the given coordinates. ([more|https://www.php.net/manual/en/function.imagestringup])


toString(int $type=Image::JPEG, ?int $quality=null): string .[method]
---------------------------------------------------------------------
Outputs an image to string.

The compression quality is in the range 0..100 for JPEG (default 85), WEBP (default 80) and AVIF (default 30) and 0..9 for PNG (default 9). Type is one of the constants `Image::JPEG`, `Image::PNG`, `Image::GIF`, `Image::WEBP`, `Image::AVIF` and `Image::BMP`.


trueColorToPalette(bool $dither, int $ncolors): void .[method]
--------------------------------------------------------------
Converts a truecolor image to a palette image. ([more|https://www.php.net/manual/en/function.imagetruecolortopalette])


ttfText(int $size, int $angle, int $x, int $y, int $color, string $fontfile, string $text): array .[method]
-----------------------------------------------------------------------------------------------------------
Writes the given text into the image using TrueType fonts. ([more|https://www.php.net/manual/en/function.imagettftext])

Image Functions

The Nette\Utils\Image class simplifies image manipulation, such as resizing, cropping, sharpening, drawing, or merging multiple images.

PHP has an extensive set of functions for manipulating images. But the API is not very nice. It wouldn't be a Nette Framework to come up with a sexy API.

Installation:

composer require nette/utils

Following examples assume the following class alias is defined:

use Nette\Utils\Image;

Creating an Image

We'll create a new true color image, for example with dimensions of 100×200:

$image = Image::fromBlank(100, 200);

Optionally, you can specify a background color (default is black):

$image = Image::fromBlank(100, 200, Image::rgb(125, 0, 0));

Or we load the image from a file:

$image = Image::fromFile('nette.jpg');

Supported formats are JPEG, PNG, GIF, WebP, AVIF and BMP, but your version of PHP must also support them (check the phpinfo(), section GD). Animations are not supported.

Need to detect the image format when loading? The method returns format in the second parameter:

$image = Image::fromFile('nette.jpg', $type);
// $type is Image::JPEG, Image::PNG, Image::GIF, Image::WEBP, Image::AVIF or Image::BMP

Only the detection without loading the image is done by Image::detectTypeFromFile() (as of nette/utils 3.2).

Save the Image

The image can be saved to a file:

$image->save('resampled.jpg');

We can specify compression quality in the range 0..100 for JPEG (default 85), WEBP (default 80) and AVIF (default 30) and 0..9 for PNG (default 9):

$image->save('resampled.jpg', 80); // JPEG, quality 80%

If the format is not obvious from the file extension, it can be specified by one of the constants Image::JPEG, Image::PNG, Image::GIF, Image::WEBP, Image::AVIF, and Image::BMP:

$image->save('resampled.tmp', null, Image::JPEG);

The image can be written to a variable instead of to disk:

$data = $image->toString(Image::JPEG, 80); // JPEG, quality 80%

or send directly to the browser with the appropriate HTTP header Content-Type:

// sends header Content-Type: image/png
$image->send(Image::PNG);

Image Resize

A common operation is to resize an image. The current dimensions are returned by methods getWidth() and getHeight().

The method resize() is used for resizing. This is example of proportional size change so that it does not exceed 500×300 pixels (either the width will be exactly 500px or the height will be exactly 300px, one of dimensions is calculated to maintain the aspect ratio):

$image->resize(500, 300);

It's possible to set only one dimension and the second one will be calculated:

$image->resize(500, null); // width 500px, height auto

$image->resize(null, 300); // width auto, height 300px

Any dimension can be specified in percentages:

$image->resize('75%', 300); // 75 % × 300px

The behavior of the resize function could be affected with following flags:

Flag Description
Image::FIT (default) resulting dimensions will be less or equal as specified
Image::FILL fills the target area and possibly extends it in one direction
Image::EXACT fills the whole area and cuts what exceeds
Image::SHRINK_ONLY just scales down (does not extend a small image)
Image::STRETCH does not keep the aspect ratio

The flags are passed as the third argument of the function:

$image->resize(500, 300, Image::STRETCH);

Flags can be combined:

$image->resize(500, 300, Image::SHRINK_ONLY | Image::STRETCH);

Images can be flipped vertically or horizontally by specifying one of the dimensions (or both) as a negative number:

$flipped = $image->resize(null, '-100%'); // flip vertical

$flipped = $image->resize('-100%', '-100%'); // rotate by 180°

$flipped = $image->resize(-125, 500); // resize & flip horizontal

After reducing the image we can improve it by sharpening:

$image->sharpen();

Cropping

The method crop() is used for cropping:

$image->crop($left, $top, $width, $height);

As with resize(), all values can be specified in percentages. The percentages for $left and $top are calculated from the remaining space, similar to the CSS property background-position:

$image->crop('100%', '50%', '80%', '80%');

The image can also be cropped automatically, eg cropped black edges:

$image->cropAuto(IMG_CROP_BLACK);

Method cropAuto() is an object encapsulation of the imagecropauto() function, see its documentation for more information.

Drawing and Editing

You can draw, you can write, you can use all PHP functions for working with images, such as imagefilledellipse(), but using object style:

$image->filledEllipse($cx, $cy, $width, $height, Image::rgb(255, 0, 0, 63));

See Overview of Methods.

Merge Multiple Images

You can easily place another image into the image:

$logo = Image::fromFile('logo.png');
$blank = Image::fromBlank(320, 240, Image::rgb(52, 132, 210));

// coordinates can be set also in percentage
$blank->place($logo, '80%', '80%'); // near the right bottom corner

When pasting, the alpha channel is respected, in addition, we can influence the transparency of the inserted image (we will create a so-called watermark):

$blank->place($image, '80%', '80%', 25); // transparency is 25 %

Such API is really a pleasure to use, isn't it?

Overview of Methods

static fromBlank(int $width, int $height, ?array $color=null)Image

Creates a new true color image of the given dimensions. The default color is black.

static fromFile(string $file, int &$detectedFormat=null)Image

Reads an image from a file and returns its type in $detectedFormat. The supported types are Image::JPEG, Image::PNG, Image::GIF, Image::WEBP, Image::AVIF and Image::BMP.

static fromString(string $s, int &$detectedFormat=null)Image

Reads an image from a string and returns its type in $detectedFormat. The supported types are Image::JPEG, Image::PNG, Image::GIF, Image::WEBP, Image::AVIF, and Image::BMP.

static rgb(int $red, int $green, int $blue, int $transparency=0)array

Creates a color that can be used in other methods, such as ellipse(), fill(), and so on.

static typeToExtension(int $type)string

Returns the file extension for the given Image::XXX constant.

static typeToMimeType(int $type)string

Returns the mime type for the given Image::XXX constant.

static extensionToType(string $extension)int

Returns the image type as a constant Image::XXX according to the file extension.

static detectTypeFromFile(string $file, int &$width=null, int &$height=null)?int

Returns the type of image file as Image::XXX constant and in the $width and $height parameters also its dimensions.

static detectTypeFromString(string $s, int &$width=null, int &$height=null)?int

Returns the type of image from string as Image::XXX constant and in the $width and $height parameters also its dimensions.

affine(array $affine, ?array $clip=null)Image

Return an image containing the affine transformed src image, using an optional clipping area. (more).

affineMatrixConcat(array $m1, array $m2)array

Returns the concatenation of two affine transformation matrices, what is useful if multiple transformations should be applied to the same image in one go. (more)

affineMatrixGet(int $type, ?mixed $options=null)array

Returns an affine transformation matrix. (more)

alphaBlending(bool $on): void

Allows for two different modes of drawing on truecolor images. In blending mode, the alpha channel component of the color supplied to all drawing function, such as setPixel() determines how much of the underlying color should be allowed to shine through. As a result, it automatically blends the existing color at that point with the drawing color, and stores the result in the image. The resulting pixel is opaque. In non-blending mode, the drawing color is copied literally with its alpha channel information, replacing the destination pixel. Blending mode is not available when drawing on palette images. (more)

antialias(bool $on): void

Activate the fast drawing antialiased methods for lines and wired polygons. It does not support alpha components. It works using a direct blend operation. It works only with truecolor images.

Using antialiased primitives with transparent background color can end with some unexpected results. The blend method uses the background color as any other colors. The lack of alpha component support does not allow an alpha based antialiasing method. (more)

arc(int $x, int $y, int $w, int $h, int $start, int $end, int $color)void

Draws an arc of circle centered at the given coordinates. (more)

char(int $font, int $x, int $y, string $char, int $color)void

Draws the first character of $char in the image with its upper-left at $x,$y (top left is 0, 0) with the color $color. (more)

charUp(int $font, int $x, int $y, string $char, int $color)void

Draws the character $char vertically at the specified coordinate on the given image. (more)

colorAllocate(int $red, int $green, int $blue)int

Returns a color identifier representing the color composed of the given RGB components. It must be called to create each color that is to be used in the image. (more)

colorAllocateAlpha(int $red, int $green, int $blue, int $alpha)int

Behaves identically to colorAllocate() with the addition of the transparency parameter $alpha. (more)

colorAt(int $x, int $y)int

Returns the index of the color of the pixel at the specified location in the image. If the image is a truecolor image, this function returns the RGB value of that pixel as integer. Use bitshifting and masking to access the distinct red, green and blue component values: (more)

colorClosest(int $red, int $green, int $blue)int

Returns the index of the color in the palette of the image which is „closest“ to the specified RGB value. The „distance“ between the desired color and each color in the palette is calculated as if the RGB values represented points in three-dimensional space. (more)

colorClosestAlpha(int $red, int $green, int $blue, int $alpha)int

Returns the index of the color in the palette of the image which is „closest“ to the specified RGB value and $alpha level. (more)

colorClosestHWB(int $red, int $green, int $blue)int

Get the index of the color which has the hue, white and blackness nearest the given color. (more)

colorDeallocate(int $color)void

De-allocates a color previously allocated with colorAllocate() or colorAllocateAlpha(). (more)

colorExact(int $red, int $green, int $blue)int

Returns the index of the specified color in the palette of the image. (more)

colorExactAlpha(int $red, int $green, int $blue, int $alpha)int

Returns the index of the specified color+alpha in the palette of the image. (more)

colorMatch(Image $image2)void

Makes the colors of the palette version of an image more closely match the true color version. (more)

colorResolve(int $red, int $green, int $blue)int

Returns a color index for a requested color, either the exact color or the closest possible alternative. (more)

colorResolveAlpha(int $red, int $green, int $blue, int $alpha)int

Returns a color index for a requested color, either the exact color or the closest possible alternative. (more)

colorSet(int $index, int $red, int $green, int $blue)void

This sets the specified index in the palette to the specified color. (more)

colorsForIndex(int $index)array

Gets the color for a specified index. (more)

colorsTotal(): int

Returns the number of colors in an image palette. (more)

colorTransparent(?int $color=null)int

Gets or sets the transparent color in the image. (more)

convolution(array $matrix, float $div, float $offset)void

Applies a convolution matrix on the image, using the given coefficient and offset. (more)

Requires Bundled GD extension, so it is not sure it will work everywhere.

copy(Image $src, int $dstX, int $dstY, int $srcX, int $srcY, int $srcW, int $srcH)void

Copies a part of $src onto image starting at the coordinates $srcX, $srcY with a width of $srcW and a height of $srcH. The portion defined will be copied onto the coordinates, $dstX and $dstY. (more)

copyMerge(Image $src, int $dstX, int $dstY, int $srcX, int $srcY, int $srcW, int $srcH, int $opacity)void

Copies a part of $src onto image starting at the coordinates $srcX, $srcY with a width of $srcW and a height of $srcH. The portion defined will be copied onto the coordinates, $dstX and $dstY. (more)

copyMergeGray(Image $src, int $dstX, int $dstY, int $srcX, int $srcY, int $srcW, int $srcH, int $opacity)void

Copies a part of $src onto image starting at the coordinates $srcX, $srcY with a width of $srcW and a height of $srcH. The portion defined will be copied onto the coordinates, $dstX and $dstY.

This function is identical to copyMerge() except that when merging it preserves the hue of the source by converting the destination pixels to gray scale before the copy operation. (more)

copyResampled(Image $src, int $dstX, int $dstY, int $srcX, int $srcY, int $dstW, int $dstH, int $srcW, int $srcH)void

Copies a rectangular portion of one image to another image, smoothly interpolating pixel values so that, in particular, reducing the size of an image still retains a great deal of clarity.

In other words, copyResampled() will take a rectangular area from $src of width $srcW and height $srcH at position ($srcX,$srcY) and place it in a rectangular area of image of width $dstW and height $dstH at position ($dstX,$dstY).

If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed. The coordinates refer to the upper left corner. This function can be used to copy regions within the same image but if the regions overlap the results will be unpredictable. (more)

copyResized(Image $src, int $dstX, int $dstY, int $srcX, int $srcY, int $dstW, int $dstH, int $srcW, int $srcH)void

Copies a rectangular portion of one image to another image. In other words, copyResized() will take a rectangular area from $src of width $srcW and height $srcH at position ($srcX,$srcY) and place it in a rectangular area of image of width $dstW and height $dstH at position ($dstX,$dstY).

If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed. The coordinates refer to the upper left corner. This function can be used to copy regions within the same image but if the regions overlap the results will be unpredictable. (more)

crop(int|string $left, int|string $top, int|string $width, int|string $height)Image

Crops an image to the given rectangular area. Dimensions can be passed as integers in pixels or strings in percent (i.e. '50%').

cropAuto(int $mode=-1, float $threshold=.5, int $color=-1)Image

Automatically crops an image according to the given $mode. (more)

ellipse(int $cx, int $cy, int $w, int $h, int $color)void

Draws an ellipse centered at the specified coordinates. (more)

fill(int $x, int $y, int $color)void

Performs a flood fill starting at the given coordinate (top left is 0, 0) with the given $color in the image. (more)

filledArc(int $cx, int $cy, int $w, int $h, int $s, int $e, int $color, int $style)void

Draws a partial arc centered at the specified coordinate in the image. (more)

filledEllipse(int $cx, int $cy, int $w, int $h, int $color)void

Draws an ellipse centered at the specified coordinate in the image. (more)

filledPolygon(array $points, int $numPoints, int $color)void

Creates a filled polygon in the $image. (more)

filledRectangle(int $x1, int $y1, int $x2, int $y2, int $color)void

Creates a rectangle filled with $color in the image starting at point 1 and ending at point 2. 0, 0 is the top left corner of the image. (more)

fillToBorder(int $x, int $y, int $border, int $color)void

Performs a flood fill whose border color is defined by $border. The starting point for the fill is $x, $y (top left is 0, 0) and the region is filled with color $color. (more)

filter(int $filtertype, int …$args)void

Applies the given filter $filtertype on the image. (more)

flip(int $mode): void

Flips the image using the given $mode. (more)

ftText(int $size, int $angle, int $x, int $y, int $col, string $fontFile, string $text, ?array $extrainfo=null)array

Write text to the image using fonts using FreeType 2. (more)

gammaCorrect(float $inputgamma, float $outputgamma)void

Applies gamma correction to the image given an input and an output gamma. (more)

getClip(): array

Retrieves the current clipping rectangle, i.e. the area beyond which no pixels will be drawn. (more)

getHeight(): int

Returns the height of the image.

getImageResource(): resource|GdImage

Returns the original resource.

getWidth(): int

Returns the width of the image.

interlace(?int $interlace=null)int

Turns the interlace bit on or off. If the interlace bit is set and the image is used as a JPEG image, the image is created as a progressive JPEG. (more)

isTrueColor(): bool

Finds whether the image is a truecolor. (more)

layerEffect(int $effect)void

Set the alpha blending flag to use layering effects. (more)

line(int $x1, int $y1, int $x2, int $y2, int $color)void

Draws a line between the two given points. (more)

openPolygon(array $points, int $numPoints, int $color)void

Draws an open polygon on the image. Contrary to polygon(), no line is drawn between the last and the first point. (more)

paletteCopy(Image $source)void

Copies the palette from the $source to the image. (more)

paletteToTrueColor(): void

Converts a palette based image, created by functions like create() to a true color image, like createtruecolor(). (more)

place(Image $image, int|string $left=0, int|string $top=0, int $opacity=100)Image

Copies $image to the image at the coordinates $left and $top. Coordinates can be passed as integers in pixels or strings in percent (i.e. '50%').

polygon(array $points, int $numPoints, int $color)void

Creates a polygon in the image. (more)

rectangle(int $x1, int $y1, int $x2, int $y2, int $col)void

Creates a rectangle starting at the specified coordinates. (more)

resize(int|string $width, int|string $height, int $flags=Image::FIT)Image

Scales an image, see more info. Dimensions can be passed as integers in pixels or strings in percent (i.e. '50%').

resolution(?int $resX=null, ?int $resY=null)mixed

Allows to set and get the resolution of an image in DPI (dots per inch). If none of the optional parameters is given, the current resolution is returned as indexed array. If only $resX is given, the horizontal and vertical resolution are set to this value. If both optional parameters are given, the horizontal and vertical resolution are set to these values, respectively.

The resolution is only used as meta information when images are read from and written to formats supporting this kind of information (curently PNG and JPEG). It does not affect any drawing operations. The default resolution for new images is 96 DPI. (more)

rotate(float $angle, int $backgroundColor)Image

Rotates the image using the given $angle in degrees. The center of rotation is the center of the image, and the rotated image may have different dimensions than the original image. (more)

Requires Bundled GD extension, so it is not sure it will work everywhere.

save(string $file, ?int $quality=null, ?int $type=null)void

Saves an image to a file.

The compression quality is in the range 0..100 for JPEG (default 85), WEBP (default 80) and AVIF (default 30) and 0..9 for PNG (default 9). If the type is not obvious from the file extension, you can specify it using one of the constants Image::JPEG, Image::PNG, Image::GIF, Image::WEBP, Image::AVIF, and Image::BMP.

saveAlpha(bool $saveflag)void

Sets the flag which determines whether to retain full alpha channel information (as opposed to single-color transparency) when saving PNG images.

Alphablending has to be disabled (alphaBlending(false)) to retain the alpha-channel in the first place. (more)

scale(int $newWidth, int $newHeight=-1, int $mode=IMG_BILINEAR_FIXED)Image

Scales an image using the given interpolation algorithm. (more)

send(int $type=Image::JPEG, ?int $quality=null)void

Outputs an image to the browser.

The compression quality is in the range 0..100 for JPEG (default 85), WEBP (default 80) and AVIF (default 30) and 0..9 for PNG (default 9). Type is one of the constants Image::JPEG, Image::PNG, Image::GIF, Image::WEBP, Image::AVIF and Image::BMP.

setBrush(Image $brush)void

Sets the brush image to be used by all line drawing functions (such as line() and polygon()) when drawing with the special colors IMG_COLOR_BRUSHED or IMG_COLOR_STYLEDBRUSHED. (more)

setClip(int $x1, int $y1, int $x2, int $y2)void

Sets the current clipping rectangle, i.e. the area beyond which no pixels will be drawn. (more)

setInterpolation(int $method=IMG_BILINEAR_FIXED)void

Sets the interpolation method which affects methods rotate() and affine(). (more)

setPixel(int $x, int $y, int $color)void

Draws a pixel at the specified coordinate. (more)

setStyle(array $style)void

Sets the style to be used by all line drawing functions (such as line() and polygon()) when drawing with the special color IMG_COLOR_STYLED or lines of images with color IMG_COLOR_STYLEDBRUSHED. (more)

setThickness(int $thickness)void

Sets the thickness of the lines drawn when drawing rectangles, polygons, arcs etc. to $thickness pixels. (more)

setTile(Image $tile)void

Sets the tile image to be used by all region filling functions (such as fill() and filledPolygon()) when filling with the special color IMG_COLOR_TILED.

A tile is an image used to fill an area with a repeated pattern. Any image can be used as a tile, and by setting the transparent color index of the tile image with colorTransparent(), a tile allows certain parts of the underlying area to shine through can be created. (more)

sharpen(): Image

Sharpens image a little bit.

Requires Bundled GD extension, so it is not sure it will work everywhere.

string(int $font, int $x, int $y, string $str, int $col)void

Draws a string at the given coordinates. (more)

stringUp(int $font, int $x, int $y, string $s, int $col)void

Draws a string vertically at the given coordinates. (more)

toString(int $type=Image::JPEG, ?int $quality=null)string

Outputs an image to string.

The compression quality is in the range 0..100 for JPEG (default 85), WEBP (default 80) and AVIF (default 30) and 0..9 for PNG (default 9). Type is one of the constants Image::JPEG, Image::PNG, Image::GIF, Image::WEBP, Image::AVIF and Image::BMP.

trueColorToPalette(bool $dither, int $ncolors)void

Converts a truecolor image to a palette image. (more)

ttfText(int $size, int $angle, int $x, int $y, int $color, string $fontfile, string $text)array

Writes the given text into the image using TrueType fonts. (more)