GraphicsCanvas

FinalYes

Self-contained GD image toolbox.

Wraps a single truecolour \GdImage and exposes the operations GifBuilder needs — creation, format detection, file loading, drawing, text, compositing, level adjustment, resizing and effects.

Every mutating method returns $this for chaining. Methods that must produce a differently-sized canvas (rotate, resize, crop, shear, wave) replace the internal \GdImage transparently. All canvases are always truecolour: palette sources are promoted on load, and quantising promotes them back.

Use resource() as an escape hatch when a raw \GdImage is needed by code not yet covered by this API.

Internal

not part of the TYPO3 Core API, the signatures expose raw GD semantics (colour indices, 0-127 alpha) and will be reshaped once image processing is split into per-processor strategies.

Table of Contents

Methods

allocateColor()  : int
Allocate an opaque colour and return its index.
allocateColorAlpha()  : int
Allocate a colour with transparency and return its index.
autolevels()  : self
Stretch the actual luminosity range to the full [0, 255] span, maximising contrast.
autoOrient()  : self
Apply the EXIF orientation tag from $filePath (JPEG only).
blur()  : self
Soften the image. Higher $passes = stronger blur.
canRead()  : bool
Whether the current GD build can decode the given file extension.
canWrite()  : bool
charcoal()  : self
Charcoal drawing — dark pencil lines on a light background.
colors()  : self
Reduce the image palette to $count colours (posterise). Dithering is enabled so photographic content degrades perceptually; on synthetic high-contrast images GD's median-cut may pick a different palette than IM/GM's K-means.
compositeMasked()  : self
Composite $overlay onto this canvas through $mask. White mask shows the overlay, black keeps the background, grey linearly blends. Clipped to the intersection of all three canvases.
convolve()  : self
Apply an arbitrary 3×3 convolution kernel.
copy()  : self
Copy a rectangular region from $source onto this canvas at ($dstX, $dstY).
copyResampled()  : self
Copy a region from $source, scaling it to the destination dimensions using bicubic resampling (better quality than copyResized).
copyResized()  : self
Copy a region from $source, scaling it via nearest-neighbour (fast, no interpolation). Use copyResampled() for better quality.
create()  : self
Create a truecolour canvas filled with the given colour. $alpha is GD-style: 0 = opaque, 127 = fully transparent. When $alpha > 0 the canvas is configured to preserve the alpha channel on save.
crop()  : self
Crop to the rectangle at ($x, $y) with dimensions $width × $height.
disableAlpha()  : self
Drop the alpha channel on save and blend onto the existing content instead — the counterpart of enableAlpha() and the mode the pixel filters need, since a convolution over pre-multiplied pixels has no meaningful result.
drawString()  : self
Render a text string using one of GD's built-in bitmap fonts (0–5).
duplicate()  : self
Return a deep copy of this canvas as a new independent instance.
edge()  : self
Edge detection. Flat regions become black; edges show up as coloured lines preserving the original hue.
ellipse()  : self
Draw an ellipse outline centred at ($cx, $cy).
emboss()  : self
Bas-relief / faux-3D effect — edges become highlights and shadows.
enableAlpha()  : self
Preserve the full alpha channel on save and disable blending so pixels are written verbatim (useful when building masks or stamping pre-multiplied layers).
enableBlending()  : self
Enable alpha blending so subsequent draw calls composite onto the existing content using the source pixel's alpha value.
fillEllipse()  : self
Fill an ellipse centred at ($cx, $cy).
fillRect()  : self
Fill a rectangle.
findClosestColor()  : int
Return the palette index of the colour closest to ($r, $g, $b).
findExactColor()  : int
Return the palette index of an exact ($r, $g, $b) match, or -1 if the colour is not in the palette.
flattenToWhite()  : self
Flatten transparency onto a white background and return a new canvas. Used when saving to JPEG.
flip()  : self
flood()  : self
Flood-fill the canvas starting at ($x, $y) with $color.
flop()  : self
gamma()  : self
Adjust midtone brightness via gamma correction. $outputGamma below 1.0 darkens midtones, above 1.0 brightens them.
getPixel()  : int
Return the raw colour integer at ($x, $y).
grayscale()  : self
height()  : int
inputLevels()  : self
Stretch the range [$low, $high] to [0, 255] (Photoshop-style Input Levels). Increases contrast; operates per RGB channel.
invert()  : self
isAvailable()  : bool
Whether the GD extension is available in this PHP build.
line()  : self
Draw a line between two points.
load()  : self
Load an existing \GdImage resource into a canvas.
loadFile()  : self|null
Load an image file. Palette images are promoted to truecolour on load so every downstream operation can assume a uniform format.
measureText()  : array<string|int, mixed>|null
Measure a TrueType text string without drawing it. Returns the 8-element bounding box from imagettfbbox(), or null on failure.
outputLevels()  : self
Compress [0, 255] into [$low, $high] (Photoshop-style Output Levels).
rect()  : self
Draw a rectangle outline.
remapColors()  : self
Replace every pixel matching one of $sourceColors with $targetColor.
renderText()  : self
Render a TrueType text string. ($x, $y) is the baseline start.
resizeTo()  : self
Resize to $width × $height using bicubic resampling. Alpha preserved.
resource()  : GdImage
Return the underlying \GdImage for use with GD functions not yet covered by this API.
rotate()  : self
Rotate counter-clockwise by $angle degrees. The canvas grows to fit the rotated image; exposed corners become fully transparent.
saveToFile()  : bool
Write the canvas to $path. Format is taken from $format, falling back to the file extension. Supports gif/jpg/png/webp/avif.
setInterlace()  : self
Enable or disable interlacing (progressive scan for JPEG/PNG).
setPixel()  : self
setTransparentColor()  : self
Define one colour index as the transparent colour (palette-mode semantics). Pass -1 to remove transparency.
sharpen()  : self
Accentuate edges to make the image look crisper. $amount is 0–100.
shear()  : self
Horizontal shear by $angle degrees. Clamped to ±85 — at ±90 the tangent diverges and the canvas would collapse to zero width.
solarize()  : self
Partial-negative / darkroom effect. $percent is 0–99 — channels brighter than that percentage of full intensity are inverted.
swirl()  : self
Twirl pixels around the centre. $degrees is the rotation at the centre; the falloff is quadratic so the corners stay still.
wave()  : self
Sinusoidal wave distortion. The canvas grows by 2 × $amplitude to avoid clipping the displaced rows.
width()  : int

Methods

allocateColor()

Allocate an opaque colour and return its index.

public allocateColor(int $r, int $g, int $b) : int

Returns -1 if allocation fails (palette exhausted).

Parameters
$r : int
$g : int
$b : int
Return values
int

allocateColorAlpha()

Allocate a colour with transparency and return its index.

public allocateColorAlpha(int $r, int $g, int $b, int $alpha) : int

$alpha ranges from 0 (fully opaque) to 127 (fully transparent). Returns -1 if allocation fails.

Parameters
$r : int
$g : int
$b : int
$alpha : int
Return values
int

autolevels()

Stretch the actual luminosity range to the full [0, 255] span, maximising contrast.

public autolevels() : self
Return values
self

autoOrient()

Apply the EXIF orientation tag from $filePath (JPEG only).

public autoOrient(string $filePath) : self

Silently skips if the exif extension is unavailable.

Parameters
$filePath : string
Return values
self

blur()

Soften the image. Higher $passes = stronger blur.

public blur([int $passes = 1 ]) : self
Parameters
$passes : int = 1
Return values
self

canRead()

Whether the current GD build can decode the given file extension.

public static canRead(string $ext) : bool

GD reads and writes the same set of formats, so canRead() and canWrite() are equivalent — both are provided for semantic clarity.

Parameters
$ext : string
Return values
bool

canWrite()

public static canWrite(string $ext) : bool
Parameters
$ext : string
Return values
bool

charcoal()

Charcoal drawing — dark pencil lines on a light background.

public charcoal([int $radius = 1 ]) : self

$radius is 1–5 (1 = sharp sketch, 5 = soft and abstract).

Parameters
$radius : int = 1
Return values
self

colors()

Reduce the image palette to $count colours (posterise). Dithering is enabled so photographic content degrades perceptually; on synthetic high-contrast images GD's median-cut may pick a different palette than IM/GM's K-means.

public colors(int $count) : self
Parameters
$count : int
Return values
self

compositeMasked()

Composite $overlay onto this canvas through $mask. White mask shows the overlay, black keeps the background, grey linearly blends. Clipped to the intersection of all three canvases.

public compositeMasked(self $overlay, self $mask) : self
Parameters
$overlay : self
$mask : self
Return values
self

convolve()

Apply an arbitrary 3×3 convolution kernel.

public convolve(array<string|int, array<string|int, float>> $matrix, float $divisor, float $offset) : self
Parameters
$matrix : array<string|int, array<string|int, float>>
$divisor : float
$offset : float
Return values
self

copy()

Copy a rectangular region from $source onto this canvas at ($dstX, $dstY).

public copy(self $source, int $dstX, int $dstY, int $srcX, int $srcY, int $w, int $h) : self
Parameters
$source : self
$dstX : int
$dstY : int
$srcX : int
$srcY : int
$w : int
$h : int
Return values
self

copyResampled()

Copy a region from $source, scaling it to the destination dimensions using bicubic resampling (better quality than copyResized).

public copyResampled(self $source, int $dstX, int $dstY, int $srcX, int $srcY, int $dstW, int $dstH, int $srcW, int $srcH) : self
Parameters
$source : self
$dstX : int
$dstY : int
$srcX : int
$srcY : int
$dstW : int
$dstH : int
$srcW : int
$srcH : int
Return values
self

copyResized()

Copy a region from $source, scaling it via nearest-neighbour (fast, no interpolation). Use copyResampled() for better quality.

public copyResized(self $source, int $dstX, int $dstY, int $srcX, int $srcY, int $dstW, int $dstH, int $srcW, int $srcH) : self
Parameters
$source : self
$dstX : int
$dstY : int
$srcX : int
$srcY : int
$dstW : int
$dstH : int
$srcW : int
$srcH : int
Return values
self

create()

Create a truecolour canvas filled with the given colour. $alpha is GD-style: 0 = opaque, 127 = fully transparent. When $alpha > 0 the canvas is configured to preserve the alpha channel on save.

public static create(int $width, int $height[, int $r = 255 ][, int $g = 255 ][, int $b = 255 ][, int $alpha = 0 ]) : self
Parameters
$width : int
$height : int
$r : int = 255
$g : int = 255
$b : int = 255
$alpha : int = 0
Return values
self

crop()

Crop to the rectangle at ($x, $y) with dimensions $width × $height.

public crop(int $x, int $y, int $width, int $height) : self
Parameters
$x : int
$y : int
$width : int
$height : int
Return values
self

disableAlpha()

Drop the alpha channel on save and blend onto the existing content instead — the counterpart of enableAlpha() and the mode the pixel filters need, since a convolution over pre-multiplied pixels has no meaningful result.

public disableAlpha() : self
Return values
self

drawString()

Render a text string using one of GD's built-in bitmap fonts (0–5).

public drawString(int $font, int $x, int $y, string $text, int $color) : self

Font 0 uses the default font; fonts 1–5 are progressively larger. Intended for simple diagnostic or placeholder images where a TTF font file is not available.

Parameters
$font : int
$x : int
$y : int
$text : string
$color : int
Return values
self

duplicate()

Return a deep copy of this canvas as a new independent instance.

public duplicate() : self
Return values
self

edge()

Edge detection. Flat regions become black; edges show up as coloured lines preserving the original hue.

public edge() : self
Return values
self

ellipse()

Draw an ellipse outline centred at ($cx, $cy).

public ellipse(int $cx, int $cy, int $w, int $h, int $color) : self
Parameters
$cx : int
$cy : int
$w : int
$h : int
$color : int
Return values
self

emboss()

Bas-relief / faux-3D effect — edges become highlights and shadows.

public emboss() : self
Return values
self

enableAlpha()

Preserve the full alpha channel on save and disable blending so pixels are written verbatim (useful when building masks or stamping pre-multiplied layers).

public enableAlpha() : self
Return values
self

enableBlending()

Enable alpha blending so subsequent draw calls composite onto the existing content using the source pixel's alpha value.

public enableBlending() : self
Return values
self

fillEllipse()

Fill an ellipse centred at ($cx, $cy).

public fillEllipse(int $cx, int $cy, int $w, int $h, int $color) : self
Parameters
$cx : int
$cy : int
$w : int
$h : int
$color : int
Return values
self

fillRect()

Fill a rectangle.

public fillRect(int $x, int $y, int $w, int $h, int $color) : self

$x/$y are the top-left corner; $w/$h are the dimensions.

Parameters
$x : int
$y : int
$w : int
$h : int
$color : int
Return values
self

findClosestColor()

Return the palette index of the colour closest to ($r, $g, $b).

public findClosestColor(int $r, int $g, int $b) : int

Useful for palette images where an exact match may not exist.

Parameters
$r : int
$g : int
$b : int
Return values
int

findExactColor()

Return the palette index of an exact ($r, $g, $b) match, or -1 if the colour is not in the palette.

public findExactColor(int $r, int $g, int $b) : int
Parameters
$r : int
$g : int
$b : int
Return values
int

flattenToWhite()

Flatten transparency onto a white background and return a new canvas. Used when saving to JPEG.

public flattenToWhite() : self
Return values
self

flip()

public flip() : self
Return values
self

flood()

Flood-fill the canvas starting at ($x, $y) with $color.

public flood(int $x, int $y, int $color) : self
Parameters
$x : int
$y : int
$color : int
Return values
self

flop()

public flop() : self
Return values
self

gamma()

Adjust midtone brightness via gamma correction. $outputGamma below 1.0 darkens midtones, above 1.0 brightens them.

public gamma(float $inputGamma, float $outputGamma) : self
Parameters
$inputGamma : float
$outputGamma : float
Return values
self

getPixel()

Return the raw colour integer at ($x, $y).

public getPixel(int $x, int $y) : int

On truecolour images this encodes as 0xAARRGGBB (GD convention: alpha in the high 7 bits, 0 = opaque). Returns 0 on failure.

Parameters
$x : int
$y : int
Return values
int

grayscale()

public grayscale() : self
Return values
self

height()

public height() : int
Return values
int

inputLevels()

Stretch the range [$low, $high] to [0, 255] (Photoshop-style Input Levels). Increases contrast; operates per RGB channel.

public inputLevels(int $low, int $high) : self
Parameters
$low : int
$high : int
Return values
self

invert()

public invert() : self
Return values
self

isAvailable()

Whether the GD extension is available in this PHP build.

public static isAvailable() : bool

Check this before calling any factory method when GD may be absent.

Return values
bool

line()

Draw a line between two points.

public line(int $x1, int $y1, int $x2, int $y2, int $color) : self
Parameters
$x1 : int
$y1 : int
$x2 : int
$y2 : int
$color : int
Return values
self

load()

Load an existing \GdImage resource into a canvas.

public static load(GdImage $image) : self
Parameters
$image : GdImage
Return values
self

loadFile()

Load an image file. Palette images are promoted to truecolour on load so every downstream operation can assume a uniform format.

public static loadFile(string $filePath[, bool $preserveAlpha = false ][, bool $autoOrient = false ]) : self|null

Returns null when the extension is unsupported or the file cannot be decoded.

Parameters
$filePath : string
$preserveAlpha : bool = false
$autoOrient : bool = false
Return values
self|null

measureText()

Measure a TrueType text string without drawing it. Returns the 8-element bounding box from imagettfbbox(), or null on failure.

public static measureText(float $size, float $angle, string $fontFile, string $text) : array<string|int, mixed>|null
Parameters
$size : float
$angle : float
$fontFile : string
$text : string
Return values
array<string|int, mixed>|null

outputLevels()

Compress [0, 255] into [$low, $high] (Photoshop-style Output Levels).

public outputLevels(int $low, int $high) : self

Reduces contrast; operates per RGB channel.

Parameters
$low : int
$high : int
Return values
self

rect()

Draw a rectangle outline.

public rect(int $x, int $y, int $w, int $h, int $color) : self

$x/$y are the top-left corner; $w/$h are the dimensions.

Parameters
$x : int
$y : int
$w : int
$h : int
$color : int
Return values
self

remapColors()

Replace every pixel matching one of $sourceColors with $targetColor.

public remapColors(array<int, array{0: int, 1: int, 2: int}> $sourceColors, array{0: int, 1: int, 2: int} $targetColor) : self

Palette images get the cheap path via imagecolorset(); truecolour images get a per-pixel scan with a hashed lookup table.

Parameters
$sourceColors : array<int, array{0: int, 1: int, 2: int}>
$targetColor : array{0: int, 1: int, 2: int}
Return values
self

renderText()

Render a TrueType text string. ($x, $y) is the baseline start.

public renderText(float $size, float $angle, int $x, int $y, int $color, string $fontFile, string $text) : self
Parameters
$size : float
$angle : float
$x : int
$y : int
$color : int
$fontFile : string
$text : string
Return values
self

resizeTo()

Resize to $width × $height using bicubic resampling. Alpha preserved.

public resizeTo(int $width, int $height) : self
Parameters
$width : int
$height : int
Return values
self

resource()

Return the underlying \GdImage for use with GD functions not yet covered by this API.

public resource() : GdImage
Return values
GdImage

rotate()

Rotate counter-clockwise by $angle degrees. The canvas grows to fit the rotated image; exposed corners become fully transparent.

public rotate(float $angle) : self
Parameters
$angle : float
Return values
self

saveToFile()

Write the canvas to $path. Format is taken from $format, falling back to the file extension. Supports gif/jpg/png/webp/avif.

public saveToFile(string $path[, string $format = '' ][, int $quality = -1 ][, int $speed = -1 ]) : bool

$quality is -1 for the format default. $speed is avif-only. JPEG flattens transparency onto white; GIF quantises to 256 colours.

Parameters
$path : string
$format : string = ''
$quality : int = -1
$speed : int = -1
Return values
bool

setInterlace()

Enable or disable interlacing (progressive scan for JPEG/PNG).

public setInterlace(bool $enable) : self
Parameters
$enable : bool
Return values
self

setPixel()

public setPixel(int $x, int $y, int $color) : self
Parameters
$x : int
$y : int
$color : int
Return values
self

setTransparentColor()

Define one colour index as the transparent colour (palette-mode semantics). Pass -1 to remove transparency.

public setTransparentColor(int $color) : self
Parameters
$color : int
Return values
self

sharpen()

Accentuate edges to make the image look crisper. $amount is 0–100.

public sharpen(int $amount) : self
Parameters
$amount : int
Return values
self

shear()

Horizontal shear by $angle degrees. Clamped to ±85 — at ±90 the tangent diverges and the canvas would collapse to zero width.

public shear(int $angle) : self
Parameters
$angle : int
Return values
self

solarize()

Partial-negative / darkroom effect. $percent is 0–99 — channels brighter than that percentage of full intensity are inverted.

public solarize(int $percent) : self
Parameters
$percent : int
Return values
self

swirl()

Twirl pixels around the centre. $degrees is the rotation at the centre; the falloff is quadratic so the corners stay still.

public swirl(int $degrees) : self
Parameters
$degrees : int
Return values
self

wave()

Sinusoidal wave distortion. The canvas grows by 2 × $amplitude to avoid clipping the displaced rows.

public wave(int $amplitude[, int $wavelength = 30 ]) : self
Parameters
$amplitude : int
$wavelength : int = 30
Return values
self

width()

public width() : int
Return values
int
On this page

Search results