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)

version: 4.0 3.x 2.x