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;
use Nette\Utils\ImageColor;
use Nette\Utils\ImageType;
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, ImageColor::rgb(125, 0, 0));
Or we load the image from a file:
$image = Image::fromFile('nette.jpg');
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 constant:
$image->save('resampled.tmp', null, ImageType::JPEG);
The image can be written to a variable instead of to disk:
$data = $image->toString(ImageType::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(ImageType::PNG);
Formats
Supported formats are JPEG, PNG, GIF, WebP, AVIF, and BMP. However, they must also be supported by your version of PHP, which can be verified using the isTypeSupported() function. Animations are not supported.
The formats are represented by constants ImageType::JPEG
, ImageType::PNG
,
ImageType::GIF
, ImageType::WEBP
, ImageType::AVIF
, and ImageType::BMP
.
$supported = Image::isTypeSupported(ImageType::JPEG);
Need to detect the format of an image upon loading? The method returns it in the second parameter:
$image = Image::fromFile('nette.jpg', $type);
The actual detection without loading the image is performed by Image::detectTypeFromFile()
.
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 resize
can be influenced by the following flags. All but Image::Stretch
preserve the
aspect ratio.
Flag | Description |
---|---|
Image::OrSmaller (default) |
resulting dimensions will be less or equal as specified |
Image::OrBigger |
fills the target area and possibly extends it in one direction |
Image::Cover |
fills the whole area and cuts what exceeds |
Image::ShrinkOnly |
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::OrBigger);
Flags can be combined:
$image->resize(500, 300, Image::ShrinkOnly | 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.
Colors
The ImageColor::rgb()
method allows you to define a color using red, green, and blue (RGB) values. Optionally, you
can also specify a transparency value ranging from 0 (completely transparent) to 1 (fully opaque), just like in CSS.
$color = ImageColor::rgb(255, 0, 0); // Red
$transparentBlue = ImageColor::rgb(0, 0, 255, 0.5); // Semi-transparent blue
The ImageColor::hex()
method allows you to define a color using the hexadecimal format, similar to CSS. It
supports the formats #rgb
, #rrggbb
, #rgba
, and #rrggbbaa
:
$color = ImageColor::hex("#F00"); // Red
$transparentGreen = ImageColor::hex("#00FF0080"); // Semi-transparent green
Colors can be used in other methods, such as ellipse()
, fill()
, etc.
Drawing and Editing
You can draw, you can write, you can use all PHP functions for image manipulation, see Overview of methods, but in an object-oriented wrapper:
$image->filledEllipse($centerX, $centerY, $width, $height, ImageColor::rgb(255, 0, 0));
Since PHP functions for drawing rectangles are impractical due to specifying coordinates, the Image
class offers
their replacements in the form of functions rectangleWH() and filledRectangleWH().
Merge Multiple Images
You can easily place another image into the image:
$logo = Image::fromFile('logo.png');
$blank = Image::fromBlank(320, 240, ImageColor::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, ?ImageColor $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
.
static fromString (string $s, int &$detectedFormat=null): Image
Reads an image from a string and returns its type in $detectedFormat
.
static rgb (int $red, int $green, int $blue, int $transparency=0): array
This feature has been replaced by the ImageColor
class , see colors.
static typeToExtension (int $type): string
Returns the file extension for the given type.
static typeToMimeType (int $type): string
Returns the mime type for the given type.
static extensionToType (string $extension): int
Returns the image type according to the file extension.
static detectTypeFromFile (string $file, int &$width=null, int &$height=null): ?int
Returns the type of image file 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 and in the $width
and $height
parameters also its dimensions.
static isTypeSupported (int $type): bool
Determines if the given image type is supported.
static getSupportedTypes(): array
Returns an array of supported image types.
static calculateTextBox (string $text, string $fontFile, float $size, float $angle=0, array $options=[]): array
Calculates the dimensions of the rectangle that encloses the text in a specified font and size. It returns an associative array
containing the keys left
, top
, width
, height
. The left margin can be negative
if the text starts with a left overhang.
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 $centerX, int $centerY, int $width, int $height, int $startAngle, int $endAngle, ImageColor $color): void
Draws an arc of circle centered at the given coordinates. (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, ?ImageColor $color=null): Image
Automatically crops an image according to the given $mode
. (more)
ellipse (int $centerX, int $centerY, int $width, int $height, ImageColor $color): void
Draws an ellipse centered at the specified coordinates. (more)
fill (int $x, int $y, ImageColor $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 $centerX, int $centerY, int $width, int $height, int $startAngle, int $endAngle, ImageColor $color, int $style): void
Draws a partial arc centered at the specified coordinate in the image. (more)
filledEllipse (int $centerX, int $centerY, int $width, int $height, ImageColor $color): void
Draws an ellipse centered at the specified coordinate in the image. (more)
filledPolygon (array $points, ImageColor $color): void
Creates a filled polygon in the $image. (more)
filledRectangle (int $x1, int $y1, int $x2, int $y2, ImageColor $color): void
Creates a rectangle filled with $color
in the image starting at $x1
& $y1
and ending
at $x2
& $y2
. Point 0, 0 is the top left corner of the image. (more)
filledRectangleWH (int $left, int $top, int $width, int $height, ImageColor $color): void
Creates a rectangle filled with $color
in the image starting from point $left
& $top
with width $width
and height $height
. Point 0, 0 is the top left corner of the image.
fillToBorder (int $x, int $y, int $border, ImageColor $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 (float $size, float $angle, int $x, int $y, ImageColor $color, string $fontFile, string $text, array $options=[]): array
Write the text in the picture. (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, ImageColor $color): void
Draws a line between the two given points. (more)
openPolygon (array $points, ImageColor $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, ImageColor $color): void
Creates a polygon in the image. (more)
rectangle (int $x1, int $y1, int $x2, int $y2, ImageColor $color): void
Creates a rectangle starting at the specified coordinates. (more)
rectangleWH (int $left, int $top, int $width, int $height, ImageColor $color): void
Creates a rectangle at the given coordinates.
resize (int|string $width, int|string $height, int $flags=Image::OrSmaller): 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 ImageType
constants.
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=ImageType::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).
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, ImageColor $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.
toString (int $type=ImageType::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).
trueColorToPalette (bool $dither, int $ncolors): void
Converts a truecolor image to a palette image. (more)
ttfText (float $size, float $angle, int $x, int $y, ImageColor $color, string $fontFile, string $text, array $options=[]): array
Writes the given text into the image. (more)