Image Functions

The class Nette\Utils\Image is intended for basic image manipulation. It simplifies the basic operations, like image resizing, sharpening or sending the image to the browser.

Installation:

composer require nette/utils

Basic Usage

If you want to manipulate images (like scaling or sharpening of images) in PHP you must write unreadable and unintelligible code. And it wouldn't be Nette Framework if it didn't come with a better API :-)

We can start with loading of the image from a file:

use Nette\Utils\Image;

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

or we can create new blank image, with size of 100×200:

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

Optionally we can set the background color (default is black):

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

And we will write its size:

echo "Image dimensions: {$image->getWidth()} × {$image->getHeight()}";

Image Resize

The first two parameters determine width and height, the third option is for flags.

Proportional size change so that it does not exceed 50×30 pixels (either the width will be exactly 50px or the height will be exactly 30px, the second dimension is counted to maintain the aspect ratio):

$image->resize(50, 30);

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

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

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

Any dimension can be also set in percentage:

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

The behavior of the resize function could be modified 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

Flags come as a third argument of the function:

$image->resize(50, 30, Image::STRETCH);

It is possible to combine all flags:

$image->resize(50, 30, Image::SHRINK_ONLY | Image::STRETCH);

If we write one or both of the dimensions as a negative number the image will be flipped (horizontally or vertically):

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

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

$flipped = $image->resize(-125, 50); // resize & flip horizontally

Image Modification

After reducing the image we can improve it by sharpening:

$image->sharpen();

We can also trim the image by the coordinates of a rectangle:

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

The reduced image can be inserted into another one (so-called watermark).

$blank = Image::fromBlank(320, 240, Image::rgb(52, 132, 210));
$blank->place($image, 0, 0); // place into a position 0px, 0px

// coordinates can be set also in percentage
$blank->place($image, '80%', '75%', 25); // transparency is 25 %

Image Saving

The image could be saved into a file:

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

Voluntarily it's possible to set also the quality and format of the image (if the format isn't set it's detected from the file extension):

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

PNG, GIF, JPEG, and WEBP formats are supported.

Alternatively the image could be saved into a variable:

$binary = (string) $image;

or you can send it directly to the browser with the setting of the according header Content-Type:

// send it like image/jpeg
$image->send();

// send it like image/png
$image->send(Image::PNG);

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. Supported types are Image::JPEG, Image::PNG, Image::GIF, Image::WEBP and Image::BMP.

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

Reads an image from a string and returns its type in $detectedFormat. Supported types are Image::JPEG, Image::PNG, Image::GIF, Image::WEBP 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.

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, gd 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($x, $y, $w, $h, $start, $end, $color)void

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

char(int $font, $x, $y, string $char, $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, $x, $y, string $char, $color)void

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

colorAllocate($red, $green, $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($red, $green, $blue, $alpha)int

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

colorAt($x, $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($red, $green, $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($red, $green, $blue, $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($red, $green, $blue)int

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

colorDeallocate($color): void

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

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

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

colorExactAlpha($red, $green, $blue, $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($red, $green, $blue): int

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

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

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

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

This sets the specified index in the palette to the specified color. This is useful for creating flood-fill-like effects in palleted images without the overhead of performing the actual flood-fill. (more)

colorsForIndex($index): array

Gets the color for a specified index. (more)

colorsTotal(): int

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

colorTransparent($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, $dstX, $dstY, $srcX, $srcY, $srcW, $srcH)void

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

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

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

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

Copies a part of $src onto image starting at the x/y coordinates $srcX, $srcY with a width of $srcW and a height of $srcH. The portion defined will be copied onto the x/y 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, $dstX, $dstY, $srcX, $srcY, $dstW, $dstH, $srcW, $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, $dstX, $dstY, $srcX, $srcY, $dstW, $dstH, $srcW, $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($cx, $cy, $w, $h, $color)void

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

fill($x, $y, $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($cx, $cy, $w, $h, $s, $e, $color, $style)void

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

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

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

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

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

filledRectangle($x1, $y1, $x2, $y2, $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($x, $y, $border, $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($filtertype): void

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

flip(int $mode): void

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

ftText($size, $angle, $x, $y, $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($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($effect): void

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

line($x1, $y1, $x2, $y2, $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 x/y coordinates $left and $top. Coordinates can be passed as integers in pixels or strings in percent (i.e. '50%').

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

Creates a polygon in the image. (more)

psText(string $text, $font, $size, $color, $backgroundColor, $x, $y, $space = null, $tightness = null, float $angle = null, $antialiasSteps = null)array

Draws a text on an image using PostScript Type1 fonts. (more)

rectangle($x1, $y1, $x2, $y2, $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, $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.

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.

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, setting an interpolation method affects the rendering of various functions in GD, such as the rotate() function. (more)

setPixel($x, $y, $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($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 GD 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($font, $x, $y, string $str, $col)void

Draws a string at the given coordinates. (more)

stringUp($font, $x, $y, string $s, $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.

trueColorToPalette(bool $dither, $ncolors)void

Converts a truecolor image to a palette image. The code for this function was originally drawn from the Independent JPEG Group library code, which is excellent. The code has been modified to preserve as much alpha channel information as possible in the resulting palette, in addition to preserving colors as well as possible. This does not work as well as might be hoped. It is usually best to simply produce a truecolor output image instead, which guarantees the highest output quality. (more)

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

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