YaWK  24.1
Yet another WebKit
YAWK\SimpleImage Class Reference

Public Member Functions

 __construct (string $image='', array $flags=[])
 
 __destruct ()
 
 arc (int $x, int $y, int $width, int $height, int $start, int $end, string|array $color, int|string $thickness=1)
 
 autoOrient ()
 
 bestFit (int $maxWidth, int $maxHeight)
 
 blur (string $type='selective', int $passes=1)
 
 border (string|array $color, int $thickness=1)
 
 brighten (int $percentage)
 
 colorize (string|array $color)
 
 contrast (int $percentage)
 
 crop (int|float $x1, int|float $y1, int|float $x2, int|float $y2)
 
 darken (int $percentage)
 
 desaturate ()
 
 dot (int $x, int $y, string|array $color)
 
 duotone (string|array $lightColor, string|array $darkColor)
 
 edgeDetect ()
 
 ellipse (int $x, int $y, int $width, int $height, string|array $color, int|array $thickness=1)
 
 emboss ()
 
 extractColors (int $count=5, string|array $backgroundColor=null)
 
 fill (string|array $color)
 
 fitToWidth (int $width)
 
 flip (string $direction)
 
 fromDataUri (string $uri)
 
 fromFile (string $file)
 
 fromNew (int $width, int $height, string|array $color='transparent')
 
 fromString (string $string)
 
 getAspectRatio ()
 
 getColorAt (int $x, int $y)
 
 getExif ()
 
 getFlag (string $flag)
 
 getHeight ()
 
 getMimeType ()
 
 getOrientation ()
 
 getResolution ()
 
 getWidth ()
 
 invert ()
 
 line (int $x1, int $y1, int $x2, int $y2, string|array $color, int $thickness=1)
 
 maxColors (int $max, bool $dither=true)
 
 opacity (float $opacity)
 
 overlay (string|SimpleImage $overlay, string $anchor='center', float|int $opacity=1, int $xOffset=0, int $yOffset=0, bool $calculateOffsetFromEdge=false)
 
 pixelate (int $size=10)
 
 polygon (array $vertices, string|array $color, string|int|array $thickness=1)
 
 rectangle (int $x1, int $y1, int $x2, int $y2, string|array $color, string|int|array $thickness=1)
 
 resize (int $width=null, int $height=null)
 
 resolution (int $res_x, int $res_y=null)
 
 rotate (int $angle, string|array $backgroundColor='transparent')
 
 roundedRectangle (int $x1, int $y1, int $x2, int $y2, int $radius, string|array $color, string|int|array $thickness=1)
 
 sepia ()
 
 setFlag (string $flag, bool $value)
 
 sharpen (int $amount=50)
 
 sketch ()
 
 text (string $text, array $options, array &$boundary=null)
 
 textBox (string $text, array $options)
 
 thumbnail (int $width, int $height, string $anchor='center')
 
 toDataUri (string $mimeType=null, array|int $options=100)
 
 toDownload (string $filename, string $mimeType=null, array|int $options=100)
 
 toFile (string $file, string $mimeType=null, array|int $options=100)
 
 toScreen (string $mimeType=null, array|int $options=100)
 
 toString (string $mimeType=null, array|int $options=100)
 

Static Public Member Functions

static adjustColor (string|array $color, int $red, int $green, int $blue, int $alpha)
 
static darkenColor (string|array $color, int $amount)
 
static lightenColor (string|array $color, int $amount)
 
static normalizeColor (string|array $color)
 

Public Attributes

const ERR_FILE_NOT_FOUND = 1
 
const ERR_FONT_FILE = 2
 
const ERR_FREETYPE_NOT_ENABLED = 3
 
const ERR_GD_NOT_ENABLED = 4
 
const ERR_INVALID_COLOR = 5
 
const ERR_INVALID_DATA_URI = 6
 
const ERR_INVALID_FLAG = 12
 
const ERR_INVALID_IMAGE = 7
 
const ERR_LIB_NOT_LOADED = 8
 
const ERR_UNSUPPORTED_FORMAT = 9
 
const ERR_WEBP_NOT_ENABLED = 10
 
const ERR_WRITE = 11
 

Protected Member Functions

 allocateColor (string|array $color)
 
 generate (string $mimeType=null, array|int $options=[])
 

Static Protected Member Functions

static imageCopyMergeAlpha ($dstIm, $srcIm, int $dstX, int $dstY, int $srcX, int $srcY, int $srcW, int $srcH, int $pct)
 
static keepWithin (int|float $value, int|float $min, int|float $max)
 

Protected Attributes

null array false $exif
 
array $flags
 
 $image
 
string $mimeType
 

Private Member Functions

 excludeInsideColor (int $x, int $y, string|array $borderColor)
 
 textSeparateLines (string $text, string $fontFile, int $fontSize, int $maxWidth)
 
 textSeparateWords (string $text)
 

Detailed Description

A PHP class that makes working with images as simple as possible.

Definition at line 27 of file SimpleImage.php.

Constructor & Destructor Documentation

◆ __construct()

YAWK\SimpleImage::__construct ( string  $image = '',
array  $flags = [] 
)

Creates a new SimpleImage object.

Parameters
string$imageAn image file or a data URI to load.
array$flagsOptional override of default flags.
Exceptions
ExceptionThrown if the GD library is not found; file|URI or image data is invalid.

Definition at line 85 of file SimpleImage.php.

86  {
87  // Check for the required GD extension
88  if (extension_loaded('gd')) {
89  // Ignore JPEG warnings that cause imagecreatefromjpeg() to fail
90  ini_set('gd.jpeg_ignore_warning', '1');
91  } else {
92  throw new Exception('Required extension GD is not loaded.', self::ERR_GD_NOT_ENABLED);
93  }
94 
95  // Associative array of flags.
96  $this->flags = [
97  'sslVerify' => true, // Skip SSL peer validation
98  ];
99 
100  // Override default flag values.
101  foreach ($flags as $flag => $value) {
102  $this->setFlag($flag, $value);
103  }
104 
105  // Load an image through the constructor
106  if (preg_match('/^data:(.*?);/', $image)) {
107  $this->fromDataUri($image);
108  } elseif ($image) {
109  $this->fromFile($image);
110  }
111  }
fromFile(string $file)
setFlag(string $flag, bool $value)
fromDataUri(string $uri)
$value

References $value.

◆ __destruct()

YAWK\SimpleImage::__destruct ( )

Destroys the image resource.

Definition at line 116 of file SimpleImage.php.

117  {
118  //Check for a valid GDimage instance
119  $type_check = (gettype($this->image) == 'object' && $this->image::class == 'GdImage');
120 
121  if (is_resource($this->image) && $type_check) {
122  imagedestroy($this->image);
123  }
124  }

Member Function Documentation

◆ adjustColor()

static YAWK\SimpleImage::adjustColor ( string|array  $color,
int  $red,
int  $green,
int  $blue,
int  $alpha 
)
static

Adjusts a color by increasing/decreasing red/green/blue/alpha values independently.

Parameters
string | array$colorThe color to adjust.
int$redRed adjustment (-255 - 255).
int$greenGreen adjustment (-255 - 255).
int$blueBlue adjustment (-255 - 255).
int$alphaAlpha adjustment (-1 - 1).
Returns
int[] An RGBA color array.
Exceptions
Exception

Definition at line 2139 of file SimpleImage.php.

2139  : array
2140  {
2141  // Normalize to RGBA
2142  $color = self::normalizeColor($color);
2143 
2144  // Adjust each channel
2145  return self::normalizeColor([
2146  'red' => $color['red'] + $red,
2147  'green' => $color['green'] + $green,
2148  'blue' => $color['blue'] + $blue,
2149  'alpha' => $color['alpha'] + $alpha,
2150  ]);
2151  }
static normalizeColor(string|array $color)

◆ allocateColor()

YAWK\SimpleImage::allocateColor ( string|array  $color)
protected

Converts a "friendly color" into a color identifier for use with GD's image functions.

Parameters
string | array$colorThe color to allocate.
Exceptions
Exception

Definition at line 2100 of file SimpleImage.php.

2100  : int
2101  {
2102  $color = self::normalizeColor($color);
2103 
2104  // Was this color already allocated?
2105  $index = imagecolorexactalpha(
2106  $this->image,
2107  $color['red'],
2108  $color['green'],
2109  $color['blue'],
2110  (int) (127 - ($color['alpha'] * 127))
2111  );
2112  if ($index > -1) {
2113  // Yes, return this color index
2114  return $index;
2115  }
2116 
2117  // Allocate a new color index
2118  return imagecolorallocatealpha(
2119  $this->image,
2120  $color['red'],
2121  $color['green'],
2122  $color['blue'],
2123  127 - ($color['alpha'] * 127)
2124  );
2125  }

◆ arc()

YAWK\SimpleImage::arc ( int  $x,
int  $y,
int  $width,
int  $height,
int  $start,
int  $end,
string|array  $color,
int|string  $thickness = 1 
)

Draws an arc.

Parameters
int$xThe x coordinate of the arc's center.
int$yThe y coordinate of the arc's center.
int$widthThe width of the arc.
int$heightThe height of the arc.
int$startThe start of the arc in degrees.
int$endThe end of the arc in degrees.
string | array$colorThe arc color.
int | string$thicknessLine thickness in pixels or 'filled' (default 1).
Returns
SimpleImage
Exceptions
Exception

Definition at line 1536 of file SimpleImage.php.

1536  : static
1537  {
1538  // Allocate the color
1539  $tempColor = $this->allocateColor($color);
1540  imagesetthickness($this->image, 1);
1541 
1542  // Draw an arc
1543  if ($thickness === 'filled') {
1544  imagefilledarc($this->image, $x, $y, $width, $height, $start, $end, $tempColor, IMG_ARC_PIE);
1545  } elseif ($thickness === 1) {
1546  imagearc($this->image, $x, $y, $width, $height, $start, $end, $tempColor);
1547  } else {
1548  // New temp image
1549  $tempImage = new SimpleImage();
1550  $tempImage->fromNew($this->getWidth(), $this->getHeight());
1551 
1552  // Draw a large ellipse filled with $color (+$thickness pixels)
1553  $tempColor = $tempImage->allocateColor($color);
1554  imagefilledarc($tempImage->image, $x, $y, $width + $thickness, $height + $thickness, $start, $end, $tempColor, IMG_ARC_PIE);
1555 
1556  // Draw a smaller ellipse filled with red|blue (-$thickness pixels)
1557  $tempColor = (self::normalizeColor($color)['red'] == 255) ? 'blue' : 'red';
1558  $tempColor = $tempImage->allocateColor($tempColor);
1559  imagefilledarc($tempImage->image, $x, $y, $width - $thickness, $height - $thickness, $start, $end, $tempColor, IMG_ARC_PIE);
1560 
1561  // Replace the color of the smaller ellipse with 'transparent'
1562  $tempImage->excludeInsideColor($x, $y, $color);
1563 
1564  // Apply the temp image
1565  $this->overlay($tempImage);
1566  }
1567 
1568  return $this;
1569  }
overlay(string|SimpleImage $overlay, string $anchor='center', float|int $opacity=1, int $xOffset=0, int $yOffset=0, bool $calculateOffsetFromEdge=false)
allocateColor(string|array $color)

◆ autoOrient()

YAWK\SimpleImage::autoOrient ( )

Rotates an image so the orientation will be correct based on its exif data. It is safe to call this method on images that don't have exif data (no changes will be made).

Returns
SimpleImage
Exceptions
Exception

Definition at line 684 of file SimpleImage.php.

684  : static
685  {
686  $exif = $this->getExif();
687 
688  if (! $exif || ! isset($exif['Orientation'])) {
689  return $this;
690  }
691 
692  switch($exif['Orientation']) {
693  case 1: // Do nothing!
694  break;
695  case 2: // Flip horizontally
696  $this->flip('x');
697  break;
698  case 3: // Rotate 180 degrees
699  $this->rotate(180);
700  break;
701  case 4: // Flip vertically
702  $this->flip('y');
703  break;
704  case 5: // Rotate 90 degrees clockwise and flip vertically
705  $this->flip('y')->rotate(90);
706  break;
707  case 6: // Rotate 90 clockwise
708  $this->rotate(90);
709  break;
710  case 7: // Rotate 90 clockwise and flip horizontally
711  $this->flip('x')->rotate(90);
712  break;
713  case 8: // Rotate 90 counterclockwise
714  $this->rotate(-90);
715  break;
716  }
717 
718  return $this;
719  }
flip(string $direction)
rotate(int $angle, string|array $backgroundColor='transparent')
null array false $exif
Definition: SimpleImage.php:71

◆ bestFit()

YAWK\SimpleImage::bestFit ( int  $maxWidth,
int  $maxHeight 
)

Proportionally resize the image to fit inside a specific width and height.

Parameters
int$maxWidthThe maximum width the image can be.
int$maxHeightThe maximum height the image can be.
Returns
SimpleImage

Definition at line 728 of file SimpleImage.php.

728  : static
729  {
730  // If the image already fits, there's nothing to do
731  if ($this->getWidth() <= $maxWidth && $this->getHeight() <= $maxHeight) {
732  return $this;
733  }
734 
735  // Calculate max width or height based on orientation
736  if ($this->getOrientation() === 'portrait') {
737  $height = $maxHeight;
738  $width = (int) round($maxHeight * $this->getAspectRatio());
739  } else {
740  $width = $maxWidth;
741  $height = (int) round($maxWidth / $this->getAspectRatio());
742  }
743 
744  // Reduce to max width
745  if ($width > $maxWidth) {
746  $width = $maxWidth;
747  $height = (int) round($width / $this->getAspectRatio());
748  }
749 
750  // Reduce to max height
751  if ($height > $maxHeight) {
752  $height = $maxHeight;
753  $width = (int) round($height * $this->getAspectRatio());
754  }
755 
756  return $this->resize($width, $height);
757  }
resize(int $width=null, int $height=null)

◆ blur()

YAWK\SimpleImage::blur ( string  $type = 'selective',
int  $passes = 1 
)

Applies the blur filter.

Parameters
string$typeThe blur algorithm to use: 'selective', 'gaussian' (default 'gaussian').
int$passesThe number of time to apply the filter, enhancing the effect (default 1).
Returns
SimpleImage

Definition at line 1874 of file SimpleImage.php.

1874  : static
1875  {
1876  $filter = $type === 'gaussian' ? IMG_FILTER_GAUSSIAN_BLUR : IMG_FILTER_SELECTIVE_BLUR;
1877 
1878  for ($i = 0; $i < $passes; $i++) {
1879  imagefilter($this->image, $filter);
1880  }
1881 
1882  return $this;
1883  }
$type
$i

References $i, and $type.

◆ border()

YAWK\SimpleImage::border ( string|array  $color,
int  $thickness = 1 
)

Draws a border around the image.

Parameters
string | array$colorThe border color.
int$thicknessThe thickness of the border (default 1).
Returns
SimpleImage
Exceptions
Exception

Definition at line 1580 of file SimpleImage.php.

1580  : static
1581  {
1582  $x1 = -1;
1583  $y1 = 0;
1584  $x2 = $this->getWidth();
1585  $y2 = $this->getHeight() - 1;
1586 
1587  $color = $this->allocateColor($color);
1588  imagesetthickness($this->image, $thickness * 2);
1589  imagerectangle($this->image, $x1, $y1, $x2, $y2, $color);
1590 
1591  return $this;
1592  }

◆ brighten()

YAWK\SimpleImage::brighten ( int  $percentage)

Applies the brightness filter to brighten the image.

Parameters
int$percentagePercentage to brighten the image (0 - 100).
Returns
SimpleImage

Definition at line 1891 of file SimpleImage.php.

1891  : static
1892  {
1893  $percentage = self::keepWithin(255 * $percentage / 100, 0, 255);
1894 
1895  imagefilter($this->image, IMG_FILTER_BRIGHTNESS, $percentage);
1896 
1897  return $this;
1898  }
static keepWithin(int|float $value, int|float $min, int|float $max)

◆ colorize()

YAWK\SimpleImage::colorize ( string|array  $color)

Applies the colorize filter.

Parameters
string | array$colorThe filter color.
Returns
SimpleImage
Exceptions
Exception

Definition at line 1908 of file SimpleImage.php.

1908  : static
1909  {
1910  $color = self::normalizeColor($color);
1911 
1912  imagefilter(
1913  $this->image,
1914  IMG_FILTER_COLORIZE,
1915  $color['red'],
1916  $color['green'],
1917  $color['blue'],
1918  127 - ($color['alpha'] * 127)
1919  );
1920 
1921  return $this;
1922  }

◆ contrast()

YAWK\SimpleImage::contrast ( int  $percentage)

Applies the contrast filter.

Parameters
int$percentagePercentage to adjust (-100 - 100).
Returns
SimpleImage

Definition at line 1930 of file SimpleImage.php.

1930  : static
1931  {
1932  imagefilter($this->image, IMG_FILTER_CONTRAST, self::keepWithin($percentage, -100, 100));
1933 
1934  return $this;
1935  }

◆ crop()

YAWK\SimpleImage::crop ( int|float  $x1,
int|float  $y1,
int|float  $x2,
int|float  $y2 
)

Crop the image.

Parameters
int | float$x1Top left x coordinate.
int | float$y1Top left y coordinate.
int | float$x2Bottom right x coordinate.
int | float$y2Bottom right x coordinate.
Returns
SimpleImage

Definition at line 768 of file SimpleImage.php.

768  : static
769  {
770  // Keep crop within image dimensions
771  $x1 = self::keepWithin($x1, 0, $this->getWidth());
772  $x2 = self::keepWithin($x2, 0, $this->getWidth());
773  $y1 = self::keepWithin($y1, 0, $this->getHeight());
774  $y2 = self::keepWithin($y2, 0, $this->getHeight());
775 
776  // Avoid using native imagecrop() because of a bug with PNG transparency
777  $dstW = abs($x2 - $x1);
778  $dstH = abs($y2 - $y1);
779  $newImage = imagecreatetruecolor((int) $dstW, (int) $dstH);
780  $transparentColor = imagecolorallocatealpha($newImage, 0, 0, 0, 127);
781  imagecolortransparent($newImage, $transparentColor ?: null);
782  imagefill($newImage, 0, 0, $transparentColor);
783 
784  // Crop it
785  imagecopyresampled(
786  $newImage,
787  $this->image,
788  0,
789  0,
790  (int) round(min($x1, $x2)),
791  (int) round(min($y1, $y2)),
792  (int) $dstW,
793  (int) $dstH,
794  (int) $dstW,
795  (int) $dstH
796  );
797 
798  // Swap out the new image
799  $this->image = $newImage;
800 
801  return $this;
802  }

◆ darken()

YAWK\SimpleImage::darken ( int  $percentage)

Applies the brightness filter to darken the image.

Parameters
int$percentagePercentage to darken the image (0 - 100).
Returns
SimpleImage

Definition at line 1943 of file SimpleImage.php.

1943  : static
1944  {
1945  $percentage = self::keepWithin(255 * $percentage / 100, 0, 255);
1946 
1947  imagefilter($this->image, IMG_FILTER_BRIGHTNESS, -$percentage);
1948 
1949  return $this;
1950  }

◆ darkenColor()

static YAWK\SimpleImage::darkenColor ( string|array  $color,
int  $amount 
)
static

Darkens a color.

Parameters
string | array$colorThe color to darken.
int$amountAmount to darken (0 - 255).
Returns
int[] An RGBA color array.
Exceptions
Exception

Definition at line 2162 of file SimpleImage.php.

2162  : array
2163  {
2164  return self::adjustColor($color, -$amount, -$amount, -$amount, 0);
2165  }
static adjustColor(string|array $color, int $red, int $green, int $blue, int $alpha)

◆ desaturate()

YAWK\SimpleImage::desaturate ( )

Applies the desaturate (grayscale) filter.

Returns
SimpleImage

Definition at line 1957 of file SimpleImage.php.

1957  : static
1958  {
1959  imagefilter($this->image, IMG_FILTER_GRAYSCALE);
1960 
1961  return $this;
1962  }

◆ dot()

YAWK\SimpleImage::dot ( int  $x,
int  $y,
string|array  $color 
)

Draws a single pixel dot.

Parameters
int$xThe x coordinate of the dot.
int$yThe y coordinate of the dot.
string | array$colorThe dot color.
Returns
SimpleImage
Exceptions
Exception

Definition at line 1604 of file SimpleImage.php.

1604  : static
1605  {
1606  $color = $this->allocateColor($color);
1607  imagesetpixel($this->image, $x, $y, $color);
1608 
1609  return $this;
1610  }

◆ duotone()

YAWK\SimpleImage::duotone ( string|array  $lightColor,
string|array  $darkColor 
)

Applies a duotone filter to the image.

Parameters
string | array$lightColorThe lightest color in the duotone.
string | array$darkColorThe darkest color in the duotone.
Returns
SimpleImage
Exceptions
Exception

Definition at line 813 of file SimpleImage.php.

813  : static
814  {
815  $lightColor = self::normalizeColor($lightColor);
816  $darkColor = self::normalizeColor($darkColor);
817 
818  // Calculate averages between light and dark colors
819  $redAvg = $lightColor['red'] - $darkColor['red'];
820  $greenAvg = $lightColor['green'] - $darkColor['green'];
821  $blueAvg = $lightColor['blue'] - $darkColor['blue'];
822 
823  // Create a matrix of all possible duotone colors based on gray values
824  $pixels = [];
825  for ($i = 0; $i <= 255; $i++) {
826  $grayAvg = $i / 255;
827  $pixels['red'][$i] = $darkColor['red'] + $grayAvg * $redAvg;
828  $pixels['green'][$i] = $darkColor['green'] + $grayAvg * $greenAvg;
829  $pixels['blue'][$i] = $darkColor['blue'] + $grayAvg * $blueAvg;
830  }
831 
832  // Apply the filter pixel by pixel
833  for ($x = 0; $x < $this->getWidth(); $x++) {
834  for ($y = 0; $y < $this->getHeight(); $y++) {
835  $rgb = $this->getColorAt($x, $y);
836  $gray = min(255, round(0.299 * $rgb['red'] + 0.114 * $rgb['blue'] + 0.587 * $rgb['green']));
837  $this->dot($x, $y, [
838  'red' => $pixels['red'][$gray],
839  'green' => $pixels['green'][$gray],
840  'blue' => $pixels['blue'][$gray],
841  ]);
842  }
843  }
844 
845  return $this;
846  }
getColorAt(int $x, int $y)
dot(int $x, int $y, string|array $color)

References $i.

◆ edgeDetect()

YAWK\SimpleImage::edgeDetect ( )

Applies the edge detect filter.

Returns
SimpleImage

Definition at line 1969 of file SimpleImage.php.

1969  : static
1970  {
1971  imagefilter($this->image, IMG_FILTER_EDGEDETECT);
1972 
1973  return $this;
1974  }

◆ ellipse()

YAWK\SimpleImage::ellipse ( int  $x,
int  $y,
int  $width,
int  $height,
string|array  $color,
int|array  $thickness = 1 
)

Draws an ellipse.

Parameters
int$xThe x coordinate of the center.
int$yThe y coordinate of the center.
int$widthThe ellipse width.
int$heightThe ellipse height.
string | array$colorThe ellipse color.
int | array$thicknessLine thickness in pixels or 'filled' (default 1).
Returns
SimpleImage
Exceptions
Exception

Definition at line 1625 of file SimpleImage.php.

1625  : static
1626  {
1627  // Allocate the color
1628  $tempColor = $this->allocateColor($color);
1629  imagesetthickness($this->image, 1);
1630 
1631  // Draw an ellipse
1632  if ($thickness == 'filled') {
1633  imagefilledellipse($this->image, $x, $y, $width, $height, $tempColor);
1634  } elseif ($thickness === 1) {
1635  imageellipse($this->image, $x, $y, $width, $height, $tempColor);
1636  } else {
1637  // New temp image
1638  $tempImage = new SimpleImage();
1639  $tempImage->fromNew($this->getWidth(), $this->getHeight());
1640 
1641  // Draw a large ellipse filled with $color (+$thickness pixels)
1642  $tempColor = $tempImage->allocateColor($color);
1643  imagefilledellipse($tempImage->image, $x, $y, $width + $thickness, $height + $thickness, $tempColor);
1644 
1645  // Draw a smaller ellipse filled with red|blue (-$thickness pixels)
1646  $tempColor = (self::normalizeColor($color)['red'] == 255) ? 'blue' : 'red';
1647  $tempColor = $tempImage->allocateColor($tempColor);
1648  imagefilledellipse($tempImage->image, $x, $y, $width - $thickness, $height - $thickness, $tempColor);
1649 
1650  // Replace the color of the smaller ellipse with 'transparent'
1651  $tempImage->excludeInsideColor($x, $y, $color);
1652 
1653  // Apply the temp image
1654  $this->overlay($tempImage);
1655  }
1656 
1657  return $this;
1658  }

◆ emboss()

YAWK\SimpleImage::emboss ( )

Applies the emboss filter.

Returns
SimpleImage

Definition at line 1981 of file SimpleImage.php.

1981  : static
1982  {
1983  imagefilter($this->image, IMG_FILTER_EMBOSS);
1984 
1985  return $this;
1986  }

◆ excludeInsideColor()

YAWK\SimpleImage::excludeInsideColor ( int  $x,
int  $y,
string|array  $borderColor 
)
private

Exclude inside color. Used for roundedRectangle(), ellipse() and arc()

Parameters
int$xcerter x of rectangle.
int$ycerter y of rectangle.
string | array$borderColorThe color of border.
Exceptions
Exception

Definition at line 1854 of file SimpleImage.php.

1854  : static
1855  {
1856  $borderColor = $this->allocateColor($borderColor);
1857  $transparent = $this->allocateColor('transparent');
1858  imagefilltoborder($this->image, $x, $y, $borderColor, $transparent);
1859 
1860  return $this;
1861  }

◆ extractColors()

YAWK\SimpleImage::extractColors ( int  $count = 5,
string|array  $backgroundColor = null 
)

Extracts colors from an image like a human would do.â„¢ This method requires the third-party library \League\ColorExtractor. If you're using Composer, it will be installed for you automatically.

Parameters
int$countThe max number of colors to extract (default 5).
string | array | null$backgroundColorBy default any pixel with alpha value greater than zero will be discarded. This is because transparent colors are not perceived as is. For example, fully transparent black would be seen white on a white background. So if you want to take transparency into account, you have to specify a default background color.
Returns
int[] An array of RGBA colors arrays.
Exceptions
ExceptionThrown if library \League\ColorExtractor is missing.

Definition at line 2182 of file SimpleImage.php.

2182  : array
2183  {
2184  // Check for required library
2185  if (! class_exists('\\'.ColorExtractor::class)) {
2186  throw new Exception(
2187  'Required library \League\ColorExtractor is missing.',
2188  self::ERR_LIB_NOT_LOADED
2189  );
2190  }
2191 
2192  // Convert background color to an integer value
2193  if ($backgroundColor) {
2194  $backgroundColor = self::normalizeColor($backgroundColor);
2195  $backgroundColor = Color::fromRgbToInt([
2196  'r' => $backgroundColor['red'],
2197  'g' => $backgroundColor['green'],
2198  'b' => $backgroundColor['blue'],
2199  ]);
2200  }
2201 
2202  // Extract colors from the image
2203  $palette = Palette::fromGD($this->image, $backgroundColor);
2204  $extractor = new ColorExtractor($palette);
2205  $colors = $extractor->extract($count);
2206 
2207  // Convert colors to an RGBA color array
2208  foreach ($colors as $key => $value) {
2209  $colors[$key] = self::normalizeColor(Color::fromIntToHex($value));
2210  }
2211 
2212  return $colors;
2213  }

References $value.

◆ fill()

YAWK\SimpleImage::fill ( string|array  $color)

Fills the image with a solid color.

Parameters
string | array$colorThe fill color.
Returns
SimpleImage
Exceptions
Exception

Definition at line 1668 of file SimpleImage.php.

1668  : static
1669  {
1670  // Draw a filled rectangle over the entire image
1671  $this->rectangle(0, 0, $this->getWidth(), $this->getHeight(), 'white', 'filled');
1672 
1673  // Now flood it with the appropriate color
1674  $color = $this->allocateColor($color);
1675  imagefill($this->image, 0, 0, $color);
1676 
1677  return $this;
1678  }
rectangle(int $x1, int $y1, int $x2, int $y2, string|array $color, string|int|array $thickness=1)

◆ fitToWidth()

YAWK\SimpleImage::fitToWidth ( int  $width)

Proportionally resize the image to a specific width.

Parameters
int$widthThe width to resize the image to.
Returns
SimpleImage
Deprecated:
This method was deprecated in version 3.2.2 and will be removed in version 4.0. Please use resize(null, $height) instead.

Definition at line 858 of file SimpleImage.php.

858  : static
859  {
860  return $this->resize($width);
861  }

◆ flip()

YAWK\SimpleImage::flip ( string  $direction)

Flip the image horizontally or vertically.

Parameters
string$directionThe direction to flip: x|y|both.
Returns
SimpleImage

Definition at line 869 of file SimpleImage.php.

869  : static
870  {
871  match ($direction) {
872  'x' => imageflip($this->image, IMG_FLIP_HORIZONTAL),
873  'y' => imageflip($this->image, IMG_FLIP_VERTICAL),
874  'both' => imageflip($this->image, IMG_FLIP_BOTH),
875  default => $this,
876  };
877 
878  return $this;
879  }

◆ fromDataUri()

YAWK\SimpleImage::fromDataUri ( string  $uri)

Loads an image from a data URI.

Parameters
string$uriA data URI.
Returns
SimpleImage
Exceptions
ExceptionThrown if URI or image data is invalid.

Definition at line 171 of file SimpleImage.php.

171  : static
172  {
173  // Basic formatting check
174  preg_match('/^data:(.*?);/', $uri, $matches);
175  if (! count($matches)) {
176  throw new Exception('Invalid data URI.', self::ERR_INVALID_DATA_URI);
177  }
178 
179  // Determine mime type
180  $this->mimeType = $matches[1];
181  if (! preg_match('/^image\/(gif|jpeg|png)$/', $this->mimeType)) {
182  throw new Exception(
183  'Unsupported format: '.$this->mimeType,
184  self::ERR_UNSUPPORTED_FORMAT
185  );
186  }
187 
188  // Get image data
189  $uri = base64_decode(strval(preg_replace('/^data:(.*?);base64,/', '', $uri)));
190  $this->image = imagecreatefromstring($uri);
191  if (! $this->image) {
192  throw new Exception('Invalid image data.', self::ERR_INVALID_IMAGE);
193  }
194 
195  return $this;
196  }

◆ fromFile()

YAWK\SimpleImage::fromFile ( string  $file)

Loads an image from a file.

Parameters
string$fileThe image file to load.
Returns
SimpleImage
Exceptions
ExceptionThrown if file or image data is invalid.

Definition at line 206 of file SimpleImage.php.

206  : static
207  {
208  // Set fopen options.
209  $sslVerify = $this->getFlag('sslVerify'); // Don't perform peer validation when true
210  $opts = [
211  'ssl' => [
212  'verify_peer' => $sslVerify,
213  'verify_peer_name' => $sslVerify,
214  ],
215  ];
216 
217  // Check if the file exists and is readable.
218  $file = @file_get_contents($file, false, stream_context_create($opts));
219  if ($file === false) {
220  throw new Exception("File not found: $file", self::ERR_FILE_NOT_FOUND);
221  }
222 
223  // Create image object from string
224  $this->image = imagecreatefromstring($file);
225 
226  // Get image info
227  $info = @getimagesizefromstring($file);
228  if ($info === false) {
229  throw new Exception("Invalid image file: $file", self::ERR_INVALID_IMAGE);
230  }
231  $this->mimeType = $info['mime'];
232 
233  if (! $this->image) {
234  throw new Exception('Unsupported format: '.$this->mimeType, self::ERR_UNSUPPORTED_FORMAT);
235  }
236 
237  switch($this->mimeType) {
238  case 'image/gif':
239  // Copy the gif over to a true color image to preserve its transparency. This is a
240  // workaround to prevent imagepalettetotruecolor() from borking transparency.
241  $width = imagesx($this->image);
242  $height = imagesx($this->image);
243 
244  $gif = imagecreatetruecolor((int) $width, (int) $height);
245  $alpha = imagecolorallocatealpha($gif, 0, 0, 0, 127);
246  imagecolortransparent($gif, $alpha ?: null);
247  imagefill($gif, 0, 0, $alpha);
248 
249  imagecopy($this->image, $gif, 0, 0, 0, 0, $width, $height);
250  imagedestroy($gif);
251  break;
252  case 'image/jpeg':
253  // Load exif data from JPEG images
254  if (function_exists('exif_read_data')) {
255  $this->exif = @exif_read_data('data://image/jpeg;base64,'.base64_encode($file));
256  }
257  break;
258  }
259 
260  // Convert pallete images to true color images
261  imagepalettetotruecolor($this->image);
262 
263  return $this;
264  }
getFlag(string $flag)

◆ fromNew()

YAWK\SimpleImage::fromNew ( int  $width,
int  $height,
string|array  $color = 'transparent' 
)

Creates a new image.

Parameters
int$widthThe width of the image.
int$heightThe height of the image.
string | array$colorOptional fill color for the new image (default 'transparent').
Returns
SimpleImage
Exceptions
Exception

Definition at line 276 of file SimpleImage.php.

276  : static
277  {
278  $this->image = imagecreatetruecolor($width, $height);
279 
280  // Use PNG for dynamically created images because it's lossless and supports transparency
281  $this->mimeType = 'image/png';
282 
283  // Fill the image with color
284  $this->fill($color);
285 
286  return $this;
287  }
fill(string|array $color)

◆ fromString()

YAWK\SimpleImage::fromString ( string  $string)

Definition at line 300 of file SimpleImage.php.

300  : SimpleImage|static
301  {
302  return $this->fromFile('data://;base64,'.base64_encode($string));
303  }

◆ generate()

YAWK\SimpleImage::generate ( string  $mimeType = null,
array|int  $options = [] 
)
protected

Generates an image.

Parameters
string | null$mimeTypeThe image format to output as a mime type (defaults to the original mime type).
array | int$optionsArray or Image quality as a percentage (default 100).
Returns
array Returns an array containing the image data and mime type ['data' => '', 'mimeType' => ''].
Exceptions
ExceptionThrown when WEBP support is not enabled or unsupported format.

Definition at line 318 of file SimpleImage.php.

318  : array
319  {
320  // Format defaults to the original mime type
322 
323  $quality = null;
324  // allow $options to be an int for backwards compatibility to v3
325  if (is_int($options)) {
326  $quality = $options;
327  $options = [];
328  }
329 
330  // get quality if passed as an option
331  if (is_array($options) && array_key_exists('quality', $options)) {
332  $quality = intval($options['quality']);
333  }
334 
335  // Ensure quality is a valid integer
336  if ($quality === null) {
337  $quality = 100;
338  }
339  $quality = (int) round(self::keepWithin((int) $quality, 0, 100));
340 
341  $alpha = true;
342  // get alpha if passed as an option
343  if (is_array($options) && array_key_exists('alpha', $options)) {
344  $alpha = boolval($options['alpha']);
345  }
346 
347  $interlace = null; // keep the same
348  // get interlace if passed as an option
349  if (is_array($options) && array_key_exists('interlace', $options)) {
350  $interlace = boolval($options['interlace']);
351  }
352 
353  // get raw stream from image* functions in providing no path
354  $file = null;
355 
356  // Capture output
357  ob_start();
358 
359  // Generate the image
360  switch($mimeType) {
361  case 'image/gif':
362  imagesavealpha($this->image, $alpha);
363  imagegif($this->image, $file);
364  break;
365  case 'image/jpeg':
366  imageinterlace($this->image, $interlace);
367  imagejpeg($this->image, $file, $quality);
368  break;
369  case 'image/png':
370  $filters = -1; // imagepng default
371  // get filters if passed as an option
372  if (is_array($options) && array_key_exists('filters', $options)) {
373  $filters = intval($options['filters']);
374  }
375  // compression param is called quality in imagepng but that would be
376  // misleading in context of SimpleImage
377  $compression = -1; // defaults to zlib default which is 6
378  // get compression if passed as an option
379  if (is_array($options) && array_key_exists('compression', $options)) {
380  $compression = intval($options['compression']);
381  }
382  if ($compression !== -1) {
383  $compression = (int) round(self::keepWithin($compression, 0, 10));
384  }
385  imagesavealpha($this->image, $alpha);
386  imagepng($this->image, $file, $compression, $filters);
387  break;
388  case 'image/webp':
389  // Not all versions of PHP will have webp support enabled
390  if (! function_exists('imagewebp')) {
391  throw new Exception(
392  'WEBP support is not enabled in your version of PHP.',
393  self::ERR_WEBP_NOT_ENABLED
394  );
395  }
396  // useless but recommended, see https://www.php.net/manual/en/function.imagesavealpha.php
397  imagesavealpha($this->image, $alpha);
398  imagewebp($this->image, $file, $quality);
399  break;
400  case 'image/bmp':
401  case 'image/x-ms-bmp':
402  case 'image/x-windows-bmp':
403  // Not all versions of PHP support bmp
404  if (! function_exists('imagebmp')) {
405  throw new Exception(
406  'BMP support is not available in your version of PHP.',
407  self::ERR_UNSUPPORTED_FORMAT
408  );
409  }
410  $compression = true; // imagebmp default
411  // get compression if passed as an option
412  if (is_array($options) && array_key_exists('compression', $options)) {
413  $compression = is_int($options['compression']) ?
414  $options['compression'] > 0 : boolval($options['compression']);
415  }
416  imageinterlace($this->image, $interlace);
417  imagebmp($this->image, $file, $compression);
418  break;
419  case 'image/avif':
420  // Not all versions of PHP support avif
421  if (! function_exists('imageavif')) {
422  throw new Exception(
423  'AVIF support is not available in your version of PHP.',
424  self::ERR_UNSUPPORTED_FORMAT
425  );
426  }
427  $speed = -1; // imageavif default
428  // get speed if passed as an option
429  if (is_array($options) && array_key_exists('speed', $options)) {
430  $speed = intval($options['speed']);
431  $speed = self::keepWithin($speed, 0, 10);
432  }
433  // useless but recommended, see https://www.php.net/manual/en/function.imagesavealpha.php
434  imagesavealpha($this->image, $alpha);
435  imageavif($this->image, $file, $quality, $speed);
436  break;
437  default:
438  throw new Exception('Unsupported format: '.$mimeType, self::ERR_UNSUPPORTED_FORMAT);
439  }
440 
441  // Stop capturing
442  $data = ob_get_contents();
443  ob_end_clean();
444 
445  return [
446  'data' => $data,
447  'mimeType' => $mimeType,
448  ];
449  }
$data
Definition: stats.php:78

References $data, and $options.

◆ getAspectRatio()

YAWK\SimpleImage::getAspectRatio ( )

Gets the image's current aspect ratio.

Returns
float|int Returns the aspect ratio as a float.

Definition at line 576 of file SimpleImage.php.

576  : float|int
577  {
578  return $this->getWidth() / $this->getHeight();
579  }

◆ getColorAt()

YAWK\SimpleImage::getColorAt ( int  $x,
int  $y 
)

Gets the RGBA value of a single pixel.

Parameters
int$xThe horizontal position of the pixel.
int$yThe vertical position of the pixel.
Returns
bool|int[] An RGBA color array or false if the x/y position is off the canvas.

Definition at line 2222 of file SimpleImage.php.

2222  : array|bool
2223  {
2224  // Coordinates must be on the canvas
2225  if ($x < 0 || $x > $this->getWidth() || $y < 0 || $y > $this->getHeight()) {
2226  return false;
2227  }
2228 
2229  // Get the color of this pixel and convert it to RGBA
2230  $color = imagecolorat($this->image, $x, $y);
2231  $rgba = imagecolorsforindex($this->image, $color);
2232  $rgba['alpha'] = 127 - ($color >> 24) & 0xFF;
2233 
2234  return $rgba;
2235  }

◆ getExif()

YAWK\SimpleImage::getExif ( )

Gets the image's exif data.

Returns
array|null Returns an array of exif data or null if no data is available.

Definition at line 586 of file SimpleImage.php.

586  : ?array
587  {
588  return $this->exif ?? null;
589  }

◆ getFlag()

YAWK\SimpleImage::getFlag ( string  $flag)

Get flag value.

Parameters
string$flagName of the flag to get.

Definition at line 154 of file SimpleImage.php.

154  : ?bool
155  {
156  return in_array($flag, array_keys($this->flags)) ? $this->flags[$flag] : null;
157  }

◆ getHeight()

YAWK\SimpleImage::getHeight ( )

Gets the image's current height.

Definition at line 594 of file SimpleImage.php.

594  : int
595  {
596  return (int) imagesy($this->image);
597  }

Referenced by YAWK\SimpleImage\overlay().

◆ getMimeType()

YAWK\SimpleImage::getMimeType ( )

Gets the mime type of the loaded image.

Definition at line 602 of file SimpleImage.php.

602  : string
603  {
604  return $this->mimeType;
605  }

◆ getOrientation()

YAWK\SimpleImage::getOrientation ( )

Gets the image's current orientation.

Returns
string One of the values: 'landscape', 'portrait', or 'square'

Definition at line 612 of file SimpleImage.php.

612  : string
613  {
614  $width = $this->getWidth();
615  $height = $this->getHeight();
616 
617  if ($width > $height) {
618  return 'landscape';
619  }
620  if ($width < $height) {
621  return 'portrait';
622  }
623 
624  return 'square';
625  }

◆ getResolution()

YAWK\SimpleImage::getResolution ( )

Gets the resolution of the image

Returns
array|bool The resolution as an array of integers: [96, 96]

Definition at line 632 of file SimpleImage.php.

632  : bool|array
633  {
634  return imageresolution($this->image);
635  }

◆ getWidth()

YAWK\SimpleImage::getWidth ( )

Gets the image's current width.

Definition at line 640 of file SimpleImage.php.

640  : int
641  {
642  return (int) imagesx($this->image);
643  }

Referenced by YAWK\SimpleImage\overlay().

◆ imageCopyMergeAlpha()

static YAWK\SimpleImage::imageCopyMergeAlpha (   $dstIm,
  $srcIm,
int  $dstX,
int  $dstY,
int  $srcX,
int  $srcY,
int  $srcW,
int  $srcH,
int  $pct 
)
staticprotected

Same as PHP's imagecopymerge, but works with transparent images. Used internally for overlay.

Parameters
resource$dstImDestination image link resource.
resource$srcImSource image link resource.
int$dstXx-coordinate of destination point.
int$dstYy-coordinate of destination point.
int$srcXx-coordinate of source point.
int$srcYy-coordinate of source point.
int$srcWSource width.
int$srcHSource height.
Returns
bool true if success.

Definition at line 662 of file SimpleImage.php.

662  : bool
663  {
664  // Are we merging with transparency?
665  if ($pct < 100) {
666  // Disable alpha blending and "colorize" the image using a transparent color
667  imagealphablending($srcIm, false);
668  imagefilter($srcIm, IMG_FILTER_COLORIZE, 0, 0, 0, round(127 * ((100 - $pct) / 100)));
669  }
670 
671  imagecopy($dstIm, $srcIm, $dstX, $dstY, $srcX, $srcY, $srcW, $srcH);
672 
673  return true;
674  }

◆ invert()

YAWK\SimpleImage::invert ( )

Inverts the image's colors.

Returns
SimpleImage

Definition at line 1993 of file SimpleImage.php.

1993  : static
1994  {
1995  imagefilter($this->image, IMG_FILTER_NEGATE);
1996 
1997  return $this;
1998  }

◆ keepWithin()

static YAWK\SimpleImage::keepWithin ( int|float  $value,
int|float  $min,
int|float  $max 
)
staticprotected

Ensures a numeric value is always within the min and max range.

Parameters
int | float$valueA numeric value to test.
int | float$minThe minimum allowed value.
int | float$maxThe maximum allowed value.

Definition at line 559 of file SimpleImage.php.

559  : int|float
560  {
561  if ($value < $min) {
562  return $min;
563  }
564  if ($value > $max) {
565  return $max;
566  }
567 
568  return $value;
569  }

References $value.

◆ lightenColor()

static YAWK\SimpleImage::lightenColor ( string|array  $color,
int  $amount 
)
static

Lightens a color.

Parameters
string | array$colorThe color to lighten.
int$amountAmount to lighten (0 - 255).
Returns
int[] An RGBA color array.
Exceptions
Exception

Definition at line 2246 of file SimpleImage.php.

2246  : array
2247  {
2248  return self::adjustColor($color, $amount, $amount, $amount, 0);
2249  }

◆ line()

YAWK\SimpleImage::line ( int  $x1,
int  $y1,
int  $x2,
int  $y2,
string|array  $color,
int  $thickness = 1 
)

Draws a line.

Parameters
int$x1The x coordinate for the first point.
int$y1The y coordinate for the first point.
int$x2The x coordinate for the second point.
int$y2The y coordinate for the second point.
string | array$colorThe line color.
int$thicknessThe line thickness (default 1).
Returns
SimpleImage
Exceptions
Exception

Definition at line 1693 of file SimpleImage.php.

1693  : static
1694  {
1695  // Allocate the color
1696  $color = $this->allocateColor($color);
1697 
1698  // Draw a line
1699  imagesetthickness($this->image, $thickness);
1700  imageline($this->image, $x1, $y1, $x2, $y2, $color);
1701 
1702  return $this;
1703  }

◆ maxColors()

YAWK\SimpleImage::maxColors ( int  $max,
bool  $dither = true 
)

Reduces the image to a maximum number of colors.

Parameters
int$maxThe maximum number of colors to use.
bool$ditherWhether or not to use a dithering effect (default true).
Returns
SimpleImage

Definition at line 888 of file SimpleImage.php.

888  : static
889  {
890  imagetruecolortopalette($this->image, $dither, max(1, $max));
891 
892  return $this;
893  }

◆ normalizeColor()

static YAWK\SimpleImage::normalizeColor ( string|array  $color)
static

Normalizes a hex or array color value to a well-formatted RGBA array.

Parameters
string | array$colorA CSS color name, hex string, or an array [red, green, blue, alpha]. You can pipe alpha transparency through hex strings and color names. For example: #fff|0.50 <– 50% white red|0.25 <– 25% red
Returns
array [red, green, blue, alpha].
Exceptions
ExceptionThrown if color value is invalid.

Definition at line 2263 of file SimpleImage.php.

2263  : array
2264  {
2265  // 140 CSS color names and hex values
2266  $cssColors = [
2267  'aliceblue' => '#f0f8ff', 'antiquewhite' => '#faebd7', 'aqua' => '#00ffff',
2268  'aquamarine' => '#7fffd4', 'azure' => '#f0ffff', 'beige' => '#f5f5dc', 'bisque' => '#ffe4c4',
2269  'black' => '#000000', 'blanchedalmond' => '#ffebcd', 'blue' => '#0000ff',
2270  'blueviolet' => '#8a2be2', 'brown' => '#a52a2a', 'burlywood' => '#deb887',
2271  'cadetblue' => '#5f9ea0', 'chartreuse' => '#7fff00', 'chocolate' => '#d2691e',
2272  'coral' => '#ff7f50', 'cornflowerblue' => '#6495ed', 'cornsilk' => '#fff8dc',
2273  'crimson' => '#dc143c', 'cyan' => '#00ffff', 'darkblue' => '#00008b', 'darkcyan' => '#008b8b',
2274  'darkgoldenrod' => '#b8860b', 'darkgray' => '#a9a9a9', 'darkgrey' => '#a9a9a9',
2275  'darkgreen' => '#006400', 'darkkhaki' => '#bdb76b', 'darkmagenta' => '#8b008b',
2276  'darkolivegreen' => '#556b2f', 'darkorange' => '#ff8c00', 'darkorchid' => '#9932cc',
2277  'darkred' => '#8b0000', 'darksalmon' => '#e9967a', 'darkseagreen' => '#8fbc8f',
2278  'darkslateblue' => '#483d8b', 'darkslategray' => '#2f4f4f', 'darkslategrey' => '#2f4f4f',
2279  'darkturquoise' => '#00ced1', 'darkviolet' => '#9400d3', 'deeppink' => '#ff1493',
2280  'deepskyblue' => '#00bfff', 'dimgray' => '#696969', 'dimgrey' => '#696969',
2281  'dodgerblue' => '#1e90ff', 'firebrick' => '#b22222', 'floralwhite' => '#fffaf0',
2282  'forestgreen' => '#228b22', 'fuchsia' => '#ff00ff', 'gainsboro' => '#dcdcdc',
2283  'ghostwhite' => '#f8f8ff', 'gold' => '#ffd700', 'goldenrod' => '#daa520', 'gray' => '#808080',
2284  'grey' => '#808080', 'green' => '#008000', 'greenyellow' => '#adff2f',
2285  'honeydew' => '#f0fff0', 'hotpink' => '#ff69b4', 'indianred ' => '#cd5c5c',
2286  'indigo ' => '#4b0082', 'ivory' => '#fffff0', 'khaki' => '#f0e68c', 'lavender' => '#e6e6fa',
2287  'lavenderblush' => '#fff0f5', 'lawngreen' => '#7cfc00', 'lemonchiffon' => '#fffacd',
2288  'lightblue' => '#add8e6', 'lightcoral' => '#f08080', 'lightcyan' => '#e0ffff',
2289  'lightgoldenrodyellow' => '#fafad2', 'lightgray' => '#d3d3d3', 'lightgrey' => '#d3d3d3',
2290  'lightgreen' => '#90ee90', 'lightpink' => '#ffb6c1', 'lightsalmon' => '#ffa07a',
2291  'lightseagreen' => '#20b2aa', 'lightskyblue' => '#87cefa', 'lightslategray' => '#778899',
2292  'lightslategrey' => '#778899', 'lightsteelblue' => '#b0c4de', 'lightyellow' => '#ffffe0',
2293  'lime' => '#00ff00', 'limegreen' => '#32cd32', 'linen' => '#faf0e6', 'magenta' => '#ff00ff',
2294  'maroon' => '#800000', 'mediumaquamarine' => '#66cdaa', 'mediumblue' => '#0000cd',
2295  'mediumorchid' => '#ba55d3', 'mediumpurple' => '#9370db', 'mediumseagreen' => '#3cb371',
2296  'mediumslateblue' => '#7b68ee', 'mediumspringgreen' => '#00fa9a',
2297  'mediumturquoise' => '#48d1cc', 'mediumvioletred' => '#c71585', 'midnightblue' => '#191970',
2298  'mintcream' => '#f5fffa', 'mistyrose' => '#ffe4e1', 'moccasin' => '#ffe4b5',
2299  'navajowhite' => '#ffdead', 'navy' => '#000080', 'oldlace' => '#fdf5e6', 'olive' => '#808000',
2300  'olivedrab' => '#6b8e23', 'orange' => '#ffa500', 'orangered' => '#ff4500',
2301  'orchid' => '#da70d6', 'palegoldenrod' => '#eee8aa', 'palegreen' => '#98fb98',
2302  'paleturquoise' => '#afeeee', 'palevioletred' => '#db7093', 'papayawhip' => '#ffefd5',
2303  'peachpuff' => '#ffdab9', 'peru' => '#cd853f', 'pink' => '#ffc0cb', 'plum' => '#dda0dd',
2304  'powderblue' => '#b0e0e6', 'purple' => '#800080', 'rebeccapurple' => '#663399',
2305  'red' => '#ff0000', 'rosybrown' => '#bc8f8f', 'royalblue' => '#4169e1',
2306  'saddlebrown' => '#8b4513', 'salmon' => '#fa8072', 'sandybrown' => '#f4a460',
2307  'seagreen' => '#2e8b57', 'seashell' => '#fff5ee', 'sienna' => '#a0522d',
2308  'silver' => '#c0c0c0', 'skyblue' => '#87ceeb', 'slateblue' => '#6a5acd',
2309  'slategray' => '#708090', 'slategrey' => '#708090', 'snow' => '#fffafa',
2310  'springgreen' => '#00ff7f', 'steelblue' => '#4682b4', 'tan' => '#d2b48c', 'teal' => '#008080',
2311  'thistle' => '#d8bfd8', 'tomato' => '#ff6347', 'turquoise' => '#40e0d0',
2312  'violet' => '#ee82ee', 'wheat' => '#f5deb3', 'white' => '#ffffff', 'whitesmoke' => '#f5f5f5',
2313  'yellow' => '#ffff00', 'yellowgreen' => '#9acd32',
2314  ];
2315 
2316  // Parse alpha from '#fff|.5' and 'white|.5'
2317  if (is_string($color) && strstr($color, '|')) {
2318  $color = explode('|', $color);
2319  $alpha = (float) $color[1];
2320  $color = trim($color[0]);
2321  } else {
2322  $alpha = 1;
2323  }
2324 
2325  // Translate CSS color names to hex values
2326  if (is_string($color) && array_key_exists(strtolower($color), $cssColors)) {
2327  $color = $cssColors[strtolower($color)];
2328  }
2329 
2330  // Translate transparent keyword to a transparent color
2331  if ($color === 'transparent') {
2332  $color = ['red' => 0, 'green' => 0, 'blue' => 0, 'alpha' => 0];
2333  }
2334 
2335  // Convert hex values to RGBA
2336  if (is_string($color)) {
2337  // Remove #
2338  $hex = strval(preg_replace('/^#/', '', $color));
2339 
2340  // Support short and standard hex codes
2341  if (strlen($hex) === 3) {
2342  [$red, $green, $blue] = [
2343  $hex[0].$hex[0],
2344  $hex[1].$hex[1],
2345  $hex[2].$hex[2],
2346  ];
2347  } elseif (strlen($hex) === 6) {
2348  [$red, $green, $blue] = [
2349  $hex[0].$hex[1],
2350  $hex[2].$hex[3],
2351  $hex[4].$hex[5],
2352  ];
2353  } else {
2354  throw new Exception("Invalid color value: $color", self::ERR_INVALID_COLOR);
2355  }
2356 
2357  // Turn color into an array
2358  $color = [
2359  'red' => hexdec($red),
2360  'green' => hexdec($green),
2361  'blue' => hexdec($blue),
2362  'alpha' => $alpha,
2363  ];
2364  }
2365 
2366  // Enforce color value ranges
2367  if (is_array($color)) {
2368  // RGB default to 0
2369  $color['red'] ??= 0;
2370  $color['green'] ??= 0;
2371  $color['blue'] ??= 0;
2372 
2373  // Alpha defaults to 1
2374  $color['alpha'] ??= 1;
2375 
2376  return [
2377  'red' => (int) self::keepWithin((int) $color['red'], 0, 255),
2378  'green' => (int) self::keepWithin((int) $color['green'], 0, 255),
2379  'blue' => (int) self::keepWithin((int) $color['blue'], 0, 255),
2380  'alpha' => self::keepWithin($color['alpha'], 0, 1),
2381  ];
2382  }
2383 
2384  throw new Exception("Invalid color value: $color", self::ERR_INVALID_COLOR);
2385  }

◆ opacity()

YAWK\SimpleImage::opacity ( float  $opacity)

Changes the image's opacity level.

Parameters
float$opacityThe desired opacity level (0 - 1).
Returns
SimpleImage
Exceptions
Exception

Definition at line 2008 of file SimpleImage.php.

2008  : static
2009  {
2010  // Create a transparent image
2011  $newImage = new SimpleImage();
2012  $newImage->fromNew($this->getWidth(), $this->getHeight());
2013 
2014  // Copy the current image (with opacity) onto the transparent image
2016  $newImage->image,
2017  $this->image,
2018  0, 0,
2019  0, 0,
2020  $this->getWidth(),
2021  $this->getHeight(),
2022  (int) round(self::keepWithin($opacity, 0, 1) * 100)
2023  );
2024 
2025  return $this;
2026  }
static imageCopyMergeAlpha($dstIm, $srcIm, int $dstX, int $dstY, int $srcX, int $srcY, int $srcW, int $srcH, int $pct)

◆ overlay()

YAWK\SimpleImage::overlay ( string|SimpleImage  $overlay,
string  $anchor = 'center',
float|int  $opacity = 1,
int  $xOffset = 0,
int  $yOffset = 0,
bool  $calculateOffsetFromEdge = false 
)

Place an image on top of the current image.

Parameters
string | SimpleImage$overlayThe image to overlay. This can be a filename, a data URI, or a SimpleImage object.
string$anchorThe anchor point: 'center', 'top', 'bottom', 'left', 'right', 'top left', 'top right', 'bottom left', 'bottom right' (default 'center').
float | int$opacityThe opacity level of the overlay 0-1 (default 1).
int$xOffsetHorizontal offset in pixels (default 0).
int$yOffsetVertical offset in pixels (default 0).
bool$calculateOffsetFromEdgeCalculate Offset referring to the edges of the image (default false).
Returns
SimpleImage
Exceptions
Exception

Definition at line 908 of file SimpleImage.php.

908  : static
909  {
910  // Load overlay image
911  if (! ($overlay instanceof SimpleImage)) {
912  $overlay = new SimpleImage($overlay);
913  }
914 
915  // Convert opacity
916  $opacity = (int) round(self::keepWithin($opacity, 0, 1) * 100);
917 
918  // Get available space
919  $spaceX = $this->getWidth() - $overlay->getWidth();
920  $spaceY = $this->getHeight() - $overlay->getHeight();
921 
922  // Set default center
923  $x = (int) round(($spaceX / 2) + ($calculateOffsetFromEdge ? 0 : $xOffset));
924  $y = (int) round(($spaceY / 2) + ($calculateOffsetFromEdge ? 0 : $yOffset));
925 
926  // Determine if top|bottom
927  if (str_contains($anchor, 'top')) {
928  $y = $yOffset;
929  } elseif (str_contains($anchor, 'bottom')) {
930  $y = $spaceY + ($calculateOffsetFromEdge ? -$yOffset : $yOffset);
931  }
932 
933  // Determine if left|right
934  if (str_contains($anchor, 'left')) {
935  $x = $xOffset;
936  } elseif (str_contains($anchor, 'right')) {
937  $x = $spaceX + ($calculateOffsetFromEdge ? -$xOffset : $xOffset);
938  }
939 
940  // Perform the overlay
942  $this->image,
943  $overlay->image,
944  $x, $y,
945  0, 0,
946  $overlay->getWidth(),
947  $overlay->getHeight(),
948  $opacity
949  );
950 
951  return $this;
952  }

References YAWK\SimpleImage\getHeight(), and YAWK\SimpleImage\getWidth().

◆ pixelate()

YAWK\SimpleImage::pixelate ( int  $size = 10)

Applies the pixelate filter.

Parameters
int$sizeThe size of the blocks in pixels (default 10).
Returns
SimpleImage

Definition at line 2034 of file SimpleImage.php.

2034  : static
2035  {
2036  imagefilter($this->image, IMG_FILTER_PIXELATE, $size, true);
2037 
2038  return $this;
2039  }

◆ polygon()

YAWK\SimpleImage::polygon ( array  $vertices,
string|array  $color,
string|int|array  $thickness = 1 
)

Draws a polygon.

Parameters
array$verticesThe polygon's vertices in an array of x/y arrays. Example: [ ['x' => x1, 'y' => y1], ['x' => x2, 'y' => y2], ['x' => xN, 'y' => yN] ]
string | array$colorThe polygon color.
string | int | array$thicknessLine thickness in pixels or 'filled' (default 1).
Returns
SimpleImage
Exceptions
Exception

Definition at line 1722 of file SimpleImage.php.

1722  : static
1723  {
1724  // Allocate the color
1725  $color = $this->allocateColor($color);
1726 
1727  // Convert [['x' => x1, 'y' => x1], ['x' => x1, 'y' => y2], ...] to [x1, y1, x2, y2, ...]
1728  $points = [];
1729  foreach ($vertices as $vals) {
1730  $points[] = $vals['x'];
1731  $points[] = $vals['y'];
1732  }
1733 
1734  // Draw a polygon
1735  if ($thickness == 'filled') {
1736  imagesetthickness($this->image, 1);
1737  imagefilledpolygon($this->image, $points, count($vertices), $color);
1738  } else {
1739  imagesetthickness($this->image, $thickness);
1740  imagepolygon($this->image, $points, count($vertices), $color);
1741  }
1742 
1743  return $this;
1744  }

◆ rectangle()

YAWK\SimpleImage::rectangle ( int  $x1,
int  $y1,
int  $x2,
int  $y2,
string|array  $color,
string|int|array  $thickness = 1 
)

Draws a rectangle.

Parameters
int$x1The upper left x coordinate.
int$y1The upper left y coordinate.
int$x2The bottom right x coordinate.
int$y2The bottom right y coordinate.
string | array$colorThe rectangle color.
string | int | array$thicknessLine thickness in pixels or 'filled' (default 1).
Returns
SimpleImage
Exceptions
Exception

Definition at line 1759 of file SimpleImage.php.

1759  : static
1760  {
1761  // Allocate the color
1762  $color = $this->allocateColor($color);
1763 
1764  // Draw a rectangle
1765  if ($thickness == 'filled') {
1766  imagesetthickness($this->image, 1);
1767  imagefilledrectangle($this->image, $x1, $y1, $x2, $y2, $color);
1768  } else {
1769  imagesetthickness($this->image, $thickness);
1770  imagerectangle($this->image, $x1, $y1, $x2, $y2, $color);
1771  }
1772 
1773  return $this;
1774  }

◆ resize()

YAWK\SimpleImage::resize ( int  $width = null,
int  $height = null 
)

Resize an image to the specified dimensions. If only one dimension is specified, the image will be resized proportionally.

Parameters
int | null$widthThe new image width.
int | null$heightThe new image height.
Returns
SimpleImage

Definition at line 961 of file SimpleImage.php.

961  : static
962  {
963  // No dimensions specified
964  if (! $width && ! $height) {
965  return $this;
966  }
967 
968  // Resize to width
969  if ($width && ! $height) {
970  $height = (int) round($width / $this->getAspectRatio());
971  }
972 
973  // Resize to height
974  if (! $width && $height) {
975  $width = (int) round($height * $this->getAspectRatio());
976  }
977 
978  // If the dimensions are the same, there's no need to resize
979  if ($this->getWidth() === $width && $this->getHeight() === $height) {
980  return $this;
981  }
982 
983  // We can't use imagescale because it doesn't seem to preserve transparency properly. The
984  // workaround is to create a new truecolor image, allocate a transparent color, and copy the
985  // image over to it using imagecopyresampled.
986  $newImage = imagecreatetruecolor($width, $height);
987  $transparentColor = imagecolorallocatealpha($newImage, 0, 0, 0, 127);
988  imagecolortransparent($newImage, $transparentColor);
989  imagefill($newImage, 0, 0, $transparentColor);
990  imagecopyresampled(
991  $newImage,
992  $this->image,
993  0, 0, 0, 0,
994  $width,
995  $height,
996  $this->getWidth(),
997  $this->getHeight()
998  );
999 
1000  // Swap out the new image
1001  $this->image = $newImage;
1002 
1003  return $this;
1004  }

◆ resolution()

YAWK\SimpleImage::resolution ( int  $res_x,
int  $res_y = null 
)

Sets an image's resolution, as per https://www.php.net/manual/en/function.imageresolution.php

Parameters
int$res_xThe horizontal resolution in DPI.
int | null$res_yThe vertical resolution in DPI
Returns
SimpleImage

Definition at line 1013 of file SimpleImage.php.

1013  : static
1014  {
1015  if (is_null($res_y)) {
1016  imageresolution($this->image, $res_x);
1017  } else {
1018  imageresolution($this->image, $res_x, $res_y);
1019  }
1020 
1021  return $this;
1022  }

◆ rotate()

YAWK\SimpleImage::rotate ( int  $angle,
string|array  $backgroundColor = 'transparent' 
)

Rotates the image.

Parameters
int$angleThe angle of rotation (-360 - 360).
string | array$backgroundColorThe background color to use for the uncovered zone area after rotation (default 'transparent').
Returns
SimpleImage
Exceptions
Exception

Definition at line 1033 of file SimpleImage.php.

1033  : static
1034  {
1035  // Rotate the image on a canvas with the desired background color
1036  $backgroundColor = $this->allocateColor($backgroundColor);
1037 
1038  $this->image = imagerotate(
1039  $this->image,
1040  -(self::keepWithin($angle, -360, 360)),
1041  $backgroundColor
1042  );
1043  imagecolortransparent($this->image, imagecolorallocatealpha($this->image, 0, 0, 0, 127));
1044 
1045  return $this;
1046  }

◆ roundedRectangle()

YAWK\SimpleImage::roundedRectangle ( int  $x1,
int  $y1,
int  $x2,
int  $y2,
int  $radius,
string|array  $color,
string|int|array  $thickness = 1 
)

Draws a rounded rectangle.

Parameters
int$x1The upper left x coordinate.
int$y1The upper left y coordinate.
int$x2The bottom right x coordinate.
int$y2The bottom right y coordinate.
int$radiusThe border radius in pixels.
string | array$colorThe rectangle color.
string | int | array$thicknessLine thickness in pixels or 'filled' (default 1).
Returns
SimpleImage
Exceptions
Exception

Definition at line 1790 of file SimpleImage.php.

1790  : static
1791  {
1792  if ($thickness == 'filled') {
1793  // Draw the filled rectangle without edges
1794  $this->rectangle($x1 + $radius + 1, $y1, $x2 - $radius - 1, $y2, $color, 'filled');
1795  $this->rectangle($x1, $y1 + $radius + 1, $x1 + $radius, $y2 - $radius - 1, $color, 'filled');
1796  $this->rectangle($x2 - $radius, $y1 + $radius + 1, $x2, $y2 - $radius - 1, $color, 'filled');
1797 
1798  // Fill in the edges with arcs
1799  $this->arc($x1 + $radius, $y1 + $radius, $radius * 2, $radius * 2, 180, 270, $color, 'filled');
1800  $this->arc($x2 - $radius, $y1 + $radius, $radius * 2, $radius * 2, 270, 360, $color, 'filled');
1801  $this->arc($x1 + $radius, $y2 - $radius, $radius * 2, $radius * 2, 90, 180, $color, 'filled');
1802  $this->arc($x2 - $radius, $y2 - $radius, $radius * 2, $radius * 2, 360, 90, $color, 'filled');
1803  } else {
1804  $offset = $thickness / 2;
1805  $x1 -= $offset;
1806  $x2 += $offset;
1807  $y1 -= $offset;
1808  $y2 += $offset;
1809  $radius = self::keepWithin($radius, 0, min(($x2 - $x1) / 2, ($y2 - $y1) / 2) - 1);
1810  $radius = (int) floor($radius);
1811  $thickness = self::keepWithin($thickness, 1, min(($x2 - $x1) / 2, ($y2 - $y1) / 2));
1812 
1813  // New temp image
1814  $tempImage = new SimpleImage();
1815  $tempImage->fromNew($this->getWidth(), $this->getHeight());
1816 
1817  // Draw a large rectangle filled with $color
1818  $tempImage->roundedRectangle($x1, $y1, $x2, $y2, $radius, $color, 'filled');
1819 
1820  // Draw a smaller rectangle filled with red|blue (-$thickness pixels on each side)
1821  $tempColor = (self::normalizeColor($color)['red'] == 255) ? 'blue' : 'red';
1822  $radius = $radius - $thickness;
1823  $radius = self::keepWithin($radius, 0, $radius);
1824  $tempImage->roundedRectangle(
1825  $x1 + $thickness,
1826  $y1 + $thickness,
1827  $x2 - $thickness,
1828  $y2 - $thickness,
1829  $radius,
1830  $tempColor,
1831  'filled'
1832  );
1833 
1834  // Replace the color of the smaller rectangle with 'transparent'
1835  $tempImage->excludeInsideColor(($x2 + $x1) / 2, ($y2 + $y1) / 2, $color);
1836 
1837  // Apply the temp image
1838  $this->overlay($tempImage);
1839  }
1840 
1841  return $this;
1842  }
arc(int $x, int $y, int $width, int $height, int $start, int $end, string|array $color, int|string $thickness=1)

◆ sepia()

YAWK\SimpleImage::sepia ( )

Simulates a sepia effect by desaturating the image and applying a sepia tone.

Returns
SimpleImage

Definition at line 2046 of file SimpleImage.php.

2046  : static
2047  {
2048  imagefilter($this->image, IMG_FILTER_GRAYSCALE);
2049  imagefilter($this->image, IMG_FILTER_COLORIZE, 70, 35, 0);
2050 
2051  return $this;
2052  }

◆ setFlag()

YAWK\SimpleImage::setFlag ( string  $flag,
bool  $value 
)

Set flag value.

Parameters
string$flagName of the flag to set.
bool$valueState of the flag.
Exceptions
ExceptionThrown if flag does not exist (no default value).

Definition at line 138 of file SimpleImage.php.

138  : void
139  {
140  // Throw if flag does not exist
141  if (! in_array($flag, array_keys($this->flags))) {
142  throw new Exception('Invalid flag.', self::ERR_INVALID_FLAG);
143  }
144 
145  // Set flag value by name
146  $this->flags[$flag] = $value;
147  }

References $value.

◆ sharpen()

YAWK\SimpleImage::sharpen ( int  $amount = 50)

Sharpens the image.

Parameters
int$amountSharpening amount (default 50).
Returns
SimpleImage

Definition at line 2060 of file SimpleImage.php.

2060  : static
2061  {
2062  // Normalize amount
2063  $amount = max(1, min(100, $amount)) / 100;
2064 
2065  $sharpen = [
2066  [-1, -1, -1],
2067  [-1, 8 / $amount, -1],
2068  [-1, -1, -1],
2069  ];
2070  $divisor = array_sum(array_map('array_sum', $sharpen));
2071 
2072  imageconvolution($this->image, $sharpen, $divisor, 0);
2073 
2074  return $this;
2075  }

◆ sketch()

YAWK\SimpleImage::sketch ( )

Applies the mean remove filter to produce a sketch effect.

Returns
SimpleImage

Definition at line 2082 of file SimpleImage.php.

2082  : static
2083  {
2084  imagefilter($this->image, IMG_FILTER_MEAN_REMOVAL);
2085 
2086  return $this;
2087  }

◆ text()

YAWK\SimpleImage::text ( string  $text,
array  $options,
array &  $boundary = null 
)

Adds text to the image.

Parameters
string$textThe desired text.
array$optionsAn array of options.
  • fontFile* (string) - The TrueType (or compatible) font file to use.
  • size (integer) - The size of the font in pixels (default 12).
  • color (string|array) - The text color (default black).
  • anchor (string) - The anchor point: 'center', 'top', 'bottom', 'left', 'right', 'top left', 'top right', 'bottom left', 'bottom right' (default 'center').
  • xOffset (integer) - The horizontal offset in pixels (default 0).
  • yOffset (integer) - The vertical offset in pixels (default 0).
  • shadow (array) - Text shadow params.
    • x* (integer) - Horizontal offset in pixels.
    • y* (integer) - Vertical offset in pixels.
    • color* (string|array) - The text shadow color.
  • $calculateOffsetFromEdge (bool) - Calculate offsets from the edge of the image (default false).
  • $baselineAlign (bool) - Align the text font with the baseline. (default true).
array | null$boundaryIf passed, this variable will contain an array with coordinates that surround the text: [x1, y1, x2, y2, width, height]. This can be used for calculating the text's position after it gets added to the image.
Returns
SimpleImage
Exceptions
Exception

Definition at line 1073 of file SimpleImage.php.

1073  : static
1074  {
1075  // Check for freetype support
1076  if (! function_exists('imagettftext')) {
1077  throw new Exception(
1078  'Freetype support is not enabled in your version of PHP.',
1079  self::ERR_FREETYPE_NOT_ENABLED
1080  );
1081  }
1082 
1083  // Default options
1084  $options = array_merge([
1085  'fontFile' => null,
1086  'size' => 12,
1087  'color' => 'black',
1088  'anchor' => 'center',
1089  'xOffset' => 0,
1090  'yOffset' => 0,
1091  'shadow' => null,
1092  'calculateOffsetFromEdge' => false,
1093  'baselineAlign' => true,
1094  ], $options);
1095 
1096  // Extract and normalize options
1097  $fontFile = $options['fontFile'];
1098  $size = ($options['size'] / 96) * 72; // Convert px to pt (72pt per inch, 96px per inch)
1099  $color = $this->allocateColor($options['color']);
1100  $anchor = $options['anchor'];
1101  $xOffset = $options['xOffset'];
1102  $yOffset = $options['yOffset'];
1103  $calculateOffsetFromEdge = $options['calculateOffsetFromEdge'];
1104  $baselineAlign = $options['baselineAlign'];
1105  $angle = 0;
1106 
1107  // Calculate the bounding box dimensions
1108  //
1109  // Since imagettfbox() returns a bounding box from the text's baseline, we can end up with
1110  // different heights for different strings of the same font size. For example, 'type' will often
1111  // be taller than 'text' because the former has a descending letter.
1112  //
1113  // To compensate for this, we created a temporary bounding box to measure the maximum height
1114  // that the font used can occupy. Based on this, we can adjust the text vertically so that it
1115  // appears inside the box with a good consistency.
1116  //
1117  // See: https://github.com/claviska/SimpleImage/issues/165
1118  //
1119 
1120  $boxText = imagettfbbox($size, $angle, $fontFile, $text);
1121  if (! $boxText) {
1122  throw new Exception("Unable to load font file: $fontFile", self::ERR_FONT_FILE);
1123  }
1124 
1125  $boxWidth = abs($boxText[4] - $boxText[0]);
1126  $boxHeight = abs($boxText[5] - $boxText[1]);
1127 
1128  // Calculate Offset referring to the edges of the image.
1129  // Just invert the value for bottom|right;
1130  if ($calculateOffsetFromEdge) {
1131  if (str_contains($anchor, 'bottom')) {
1132  $yOffset *= -1;
1133  }
1134  if (str_contains($anchor, 'right')) {
1135  $xOffset *= -1;
1136  }
1137  }
1138 
1139  // Align the text font with the baseline.
1140  // I use $yOffset to inject the vertical alignment correction value.
1141  if ($baselineAlign) {
1142  // Create a temporary box to obtain the maximum height that this font can use.
1143  $boxFull = imagettfbbox($size, $angle, $fontFile, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890');
1144  // Based on the maximum height, the text is aligned.
1145  if (str_contains($anchor, 'bottom')) {
1146  $yOffset -= $boxFull[1];
1147  } elseif (str_contains($anchor, 'top')) {
1148  $yOffset += abs($boxFull[5]) - $boxHeight;
1149  } else { // center
1150  $boxFullHeight = abs($boxFull[1]) + abs($boxFull[5]);
1151  $yOffset += ($boxFullHeight / 2) - ($boxHeight / 2) - abs($boxFull[1]);
1152  }
1153  } else {
1154  // Prevents fonts rendered outside the box boundary from being cut.
1155  // Example: 'Scriptina' font, some letters invade the space of the previous or subsequent letter.
1156  $yOffset -= $boxText[1];
1157  }
1158 
1159  // Prevents fonts rendered outside the box boundary from being cut.
1160  // Example: 'Scriptina' font, some letters invade the space of the previous or subsequent letter.
1161  $xOffset -= $boxText[0];
1162 
1163  // Determine position
1164  switch($anchor) {
1165  case 'top left':
1166  $x = $xOffset;
1167  $y = $yOffset + $boxHeight;
1168  break;
1169  case 'top right':
1170  $x = $this->getWidth() - $boxWidth + $xOffset;
1171  $y = $yOffset + $boxHeight;
1172  break;
1173  case 'top':
1174  $x = ($this->getWidth() / 2) - ($boxWidth / 2) + $xOffset;
1175  $y = $yOffset + $boxHeight;
1176  break;
1177  case 'bottom left':
1178  $x = $xOffset;
1179  $y = $this->getHeight() + $yOffset;
1180  break;
1181  case 'bottom right':
1182  $x = $this->getWidth() - $boxWidth + $xOffset;
1183  $y = $this->getHeight() + $yOffset;
1184  break;
1185  case 'bottom':
1186  $x = ($this->getWidth() / 2) - ($boxWidth / 2) + $xOffset;
1187  $y = $this->getHeight() + $yOffset;
1188  break;
1189  case 'left':
1190  $x = $xOffset;
1191  $y = ($this->getHeight() / 2) - (($boxHeight / 2) - $boxHeight) + $yOffset;
1192  break;
1193  case 'right':
1194  $x = $this->getWidth() - $boxWidth + $xOffset;
1195  $y = ($this->getHeight() / 2) - (($boxHeight / 2) - $boxHeight) + $yOffset;
1196  break;
1197  default: // center
1198  $x = ($this->getWidth() / 2) - ($boxWidth / 2) + $xOffset;
1199  $y = ($this->getHeight() / 2) - (($boxHeight / 2) - $boxHeight) + $yOffset;
1200  break;
1201  }
1202  $x = (int) round($x);
1203  $y = (int) round($y);
1204 
1205  // Pass the boundary back by reference
1206  $boundary = [
1207  'x1' => $x + $boxText[0],
1208  'y1' => $y + $boxText[1] - $boxHeight, // $y is the baseline, not the top!
1209  'x2' => $x + $boxWidth + $boxText[0],
1210  'y2' => $y + $boxText[1],
1211  'width' => $boxWidth,
1212  'height' => $boxHeight,
1213  ];
1214 
1215  // Text shadow
1216  if (is_array($options['shadow'])) {
1217  imagettftext(
1218  $this->image,
1219  $size,
1220  $angle,
1221  $x + $options['shadow']['x'],
1222  $y + $options['shadow']['y'],
1223  $this->allocateColor($options['shadow']['color']),
1224  $fontFile,
1225  $text
1226  );
1227  }
1228 
1229  // Draw the text
1230  imagettftext($this->image, $size, $angle, $x, $y, $color, $fontFile, $text);
1231 
1232  return $this;
1233  }

References $options.

◆ textBox()

YAWK\SimpleImage::textBox ( string  $text,
array  $options 
)

Adds text with a line break to the image.

Parameters
string$textThe desired text.
array$optionsAn array of options.
  • fontFile* (string) - The TrueType (or compatible) font file to use.
  • size (integer) - The size of the font in pixels (default 12).
  • color (string|array) - The text color (default black).
  • anchor (string) - The anchor point: 'center', 'top', 'bottom', 'left', 'right', 'top left', 'top right', 'bottom left', 'bottom right' (default 'center').
  • xOffset (integer) - The horizontal offset in pixels (default 0). Has no effect when anchor is 'center'.
  • yOffset (integer) - The vertical offset in pixels (default 0). Has no effect when anchor is 'center'.
  • shadow (array) - Text shadow params.
    • x* (integer) - Horizontal offset in pixels.
    • y* (integer) - Vertical offset in pixels.
    • color* (string|array) - The text shadow color.
  • $calculateOffsetFromEdge (bool) - Calculate offsets from the edge of the image (default false).
  • width (int) - Width of text box (default image width).
  • align (string) - How to align text: 'left', 'right', 'center', 'justify' (default 'left').
  • leading (float) - Increase/decrease spacing between lines of text (default 0).
  • opacity (float) - The opacity level of the text 0-1 (default 1).
Returns
SimpleImage
Exceptions
Exception

Definition at line 1260 of file SimpleImage.php.

1260  : static
1261  {
1262  // default width of image
1263  $maxWidth = $this->getWidth();
1264  // Default options
1265  $options = array_merge([
1266  'fontFile' => null,
1267  'size' => 12,
1268  'color' => 'black',
1269  'anchor' => 'center',
1270  'xOffset' => 0,
1271  'yOffset' => 0,
1272  'shadow' => null,
1273  'calculateOffsetFromEdge' => false,
1274  'width' => $maxWidth,
1275  'align' => 'left',
1276  'leading' => 0,
1277  'opacity' => 1,
1278  ], $options);
1279 
1280  // Extract and normalize options
1281  $fontFile = $options['fontFile'];
1282  $fontSize = $fontSizePx = $options['size'];
1283  $fontSize = ($fontSize / 96) * 72; // Convert px to pt (72pt per inch, 96px per inch)
1284  $color = $options['color'];
1285  $anchor = $options['anchor'];
1286  $xOffset = $options['xOffset'];
1287  $yOffset = $options['yOffset'];
1288  $shadow = $options['shadow'];
1289  $calculateOffsetFromEdge = $options['calculateOffsetFromEdge'];
1290  $maxWidth = intval($options['width']);
1291  $leading = $options['leading'];
1292  $leading = self::keepWithin($leading, ($fontSizePx * -1), $leading);
1293  $opacity = $options['opacity'];
1294 
1295  $align = $options['align'];
1296  if ($align == 'right') {
1297  $align = 'top right';
1298  } elseif ($align == 'center') {
1299  $align = 'top';
1300  } elseif ($align == 'justify') {
1301  $align = 'justify';
1302  } else {
1303  $align = 'top left';
1304  }
1305 
1306  [$lines, $isLastLine, $lastLineHeight] = self::textSeparateLines($text, $fontFile, $fontSize, $maxWidth);
1307 
1308  $maxHeight = (int) round(((is_countable($lines) ? count($lines) : 0) - 1) * ($fontSizePx * 1.2 + $leading) + $lastLineHeight);
1309 
1310  $imageText = new SimpleImage();
1311  $imageText->fromNew($maxWidth, $maxHeight);
1312 
1313  // Align left/center/right
1314  if ($align != 'justify') {
1315  foreach ($lines as $key => $line) {
1316  if ($align == 'top') {
1317  $line = trim($line);
1318  } // If is justify = 'center'
1319  $imageText->text($line, ['fontFile' => $fontFile, 'size' => $fontSizePx, 'color' => $color, 'anchor' => $align, 'xOffset' => 0, 'yOffset' => $key * ($fontSizePx * 1.2 + $leading), 'shadow' => $shadow, 'calculateOffsetFromEdge' => true]);
1320  }
1321 
1322  // Justify
1323  } else {
1324  foreach ($lines as $keyLine => $line) {
1325  // Check if there are spaces at the beginning of the sentence
1326  $spaces = 0;
1327  if (preg_match("/^\s+/", $line, $match)) {
1328  // Count spaces
1329  $spaces = strlen($match[0]);
1330  $line = ltrim($line);
1331  }
1332 
1333  // Separate words
1334  $words = preg_split("/\s+/", $line);
1335  // Include spaces with the first word
1336  $words[0] = str_repeat(' ', $spaces).$words[0];
1337 
1338  // Calculates the space occupied by all words
1339  $wordsSize = [];
1340  foreach ($words as $key => $word) {
1341  $wordBox = imagettfbbox($fontSize, 0, $fontFile, $word);
1342  $wordWidth = abs($wordBox[4] - $wordBox[0]);
1343  $wordsSize[$key] = $wordWidth;
1344  }
1345  $wordsSizeTotal = array_sum($wordsSize);
1346 
1347  // Calculates the required space between words
1348  $countWords = count($words);
1349  $wordSpacing = 0;
1350  if ($countWords > 1) {
1351  $wordSpacing = ($maxWidth - $wordsSizeTotal) / ($countWords - 1);
1352  $wordSpacing = round($wordSpacing, 3);
1353  }
1354 
1355  $xOffsetJustify = 0;
1356  foreach ($words as $key => $word) {
1357  if ($isLastLine[$keyLine]) {
1358  if ($key < (count($words) - 1)) {
1359  continue;
1360  }
1361  $word = $line;
1362  }
1363  $imageText->text($word, ['fontFile' => $fontFile, 'size' => $fontSizePx, 'color' => $color, 'anchor' => 'top left', 'xOffset' => $xOffsetJustify, 'yOffset' => $keyLine * ($fontSizePx * 1.2 + $leading), 'shadow' => $shadow, 'calculateOffsetFromEdge' => true]
1364  );
1365  // Calculate offset for next word
1366  $xOffsetJustify += $wordsSize[$key] + $wordSpacing;
1367  }
1368  }
1369  }
1370 
1371  $this->overlay($imageText, $anchor, $opacity, $xOffset, $yOffset, $calculateOffsetFromEdge);
1372 
1373  return $this;
1374  }
textSeparateLines(string $text, string $fontFile, int $fontSize, int $maxWidth)

References $options.

◆ textSeparateLines()

YAWK\SimpleImage::textSeparateLines ( string  $text,
string  $fontFile,
int  $fontSize,
int  $maxWidth 
)
private

Receives a text and breaks into LINES.

Definition at line 1379 of file SimpleImage.php.

1379  : array
1380  {
1381  $lines = [];
1382  $words = self::textSeparateWords($text);
1383  $countWords = count($words) - 1;
1384  $lines[0] = '';
1385  $lineKey = 0;
1386  $isLastLine = [];
1387  for ($i = 0; $i < $countWords; $i++) {
1388  $word = $words[$i];
1389  $isLastLine[$lineKey] = false;
1390  if ($word === PHP_EOL) {
1391  $isLastLine[$lineKey] = true;
1392  $lineKey++;
1393  $lines[$lineKey] = '';
1394 
1395  continue;
1396  }
1397  $lineBox = imagettfbbox($fontSize, 0, $fontFile, $lines[$lineKey].$word);
1398  if (abs($lineBox[4] - $lineBox[0]) < $maxWidth) {
1399  $lines[$lineKey] .= $word.' ';
1400  } else {
1401  $lineKey++;
1402  $lines[$lineKey] = $word.' ';
1403  }
1404  }
1405  $isLastLine[$lineKey] = true;
1406  // Exclude space of right
1407  $lines = array_map('rtrim', $lines);
1408  // Calculate height of last line
1409  $boxFull = imagettfbbox($fontSize, 0, $fontFile, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890');
1410  $lineBox = imagettfbbox($fontSize, 0, $fontFile, $lines[$lineKey]);
1411  // Height of last line = ascender of $boxFull + descender of $lineBox
1412  $lastLineHeight = abs($lineBox[1]) + abs($boxFull[5]);
1413 
1414  return [$lines, $isLastLine, $lastLineHeight];
1415  }
textSeparateWords(string $text)

References $i.

◆ textSeparateWords()

YAWK\SimpleImage::textSeparateWords ( string  $text)
private

Receives a text and breaks into WORD / SPACE / NEW LINE.

Definition at line 1420 of file SimpleImage.php.

1420  : array
1421  {
1422  // Normalizes line break
1423  $text = strval(preg_replace('/(\r\n|\n|\r)/', PHP_EOL, $text));
1424  $text = explode(PHP_EOL, $text);
1425  $newText = [];
1426  foreach ($text as $line) {
1427  $newText = array_merge($newText, explode(' ', $line), [PHP_EOL]);
1428  }
1429 
1430  return $newText;
1431  }

◆ thumbnail()

YAWK\SimpleImage::thumbnail ( int  $width,
int  $height,
string  $anchor = 'center' 
)

Creates a thumbnail image. This function attempts to get the image as close to the provided dimensions as possible, then crops the remaining overflow to force the desired size. Useful for generating thumbnail images.

Parameters
int$widthThe thumbnail width.
int$heightThe thumbnail height.
string$anchorThe anchor point: 'center', 'top', 'bottom', 'left', 'right', 'top left', 'top right', 'bottom left', 'bottom right' (default 'center').
Returns
SimpleImage

Definition at line 1443 of file SimpleImage.php.

1443  : SimpleImage|static
1444  {
1445  // Determine aspect ratios
1446  $currentRatio = $this->getHeight() / $this->getWidth();
1447  $targetRatio = $height / $width;
1448 
1449  // Fit to height/width
1450  if ($targetRatio > $currentRatio) {
1451  $this->resize(null, $height);
1452  } else {
1453  $this->resize($width);
1454  }
1455 
1456  switch($anchor) {
1457  case 'top':
1458  $x1 = floor(($this->getWidth() / 2) - ($width / 2));
1459  $x2 = $width + $x1;
1460  $y1 = 0;
1461  $y2 = $height;
1462  break;
1463  case 'bottom':
1464  $x1 = floor(($this->getWidth() / 2) - ($width / 2));
1465  $x2 = $width + $x1;
1466  $y1 = $this->getHeight() - $height;
1467  $y2 = $this->getHeight();
1468  break;
1469  case 'left':
1470  $x1 = 0;
1471  $x2 = $width;
1472  $y1 = floor(($this->getHeight() / 2) - ($height / 2));
1473  $y2 = $height + $y1;
1474  break;
1475  case 'right':
1476  $x1 = $this->getWidth() - $width;
1477  $x2 = $this->getWidth();
1478  $y1 = floor(($this->getHeight() / 2) - ($height / 2));
1479  $y2 = $height + $y1;
1480  break;
1481  case 'top left':
1482  $x1 = 0;
1483  $x2 = $width;
1484  $y1 = 0;
1485  $y2 = $height;
1486  break;
1487  case 'top right':
1488  $x1 = $this->getWidth() - $width;
1489  $x2 = $this->getWidth();
1490  $y1 = 0;
1491  $y2 = $height;
1492  break;
1493  case 'bottom left':
1494  $x1 = 0;
1495  $x2 = $width;
1496  $y1 = $this->getHeight() - $height;
1497  $y2 = $this->getHeight();
1498  break;
1499  case 'bottom right':
1500  $x1 = $this->getWidth() - $width;
1501  $x2 = $this->getWidth();
1502  $y1 = $this->getHeight() - $height;
1503  $y2 = $this->getHeight();
1504  break;
1505  default:
1506  $x1 = floor(($this->getWidth() / 2) - ($width / 2));
1507  $x2 = $width + $x1;
1508  $y1 = floor(($this->getHeight() / 2) - ($height / 2));
1509  $y2 = $height + $y1;
1510  break;
1511  }
1512 
1513  // Return the cropped thumbnail image
1514  return $this->crop($x1, $y1, $x2, $y2);
1515  }
crop(int|float $x1, int|float $y1, int|float $x2, int|float $y2)

◆ toDataUri()

YAWK\SimpleImage::toDataUri ( string  $mimeType = null,
array|int  $options = 100 
)

Generates a data URI.

Parameters
string | null$mimeTypeThe image format to output as a mime type (defaults to the original mime type).
array | int$optionsArray or Image quality as a percentage (default 100).
Returns
string Returns a string containing a data URI.
Exceptions
Exception

Definition at line 460 of file SimpleImage.php.

460  : string
461  {
462  $image = $this->generate($mimeType, $options);
463 
464  return 'data:'.$image['mimeType'].';base64,'.base64_encode($image['data']);
465  }
generate(string $mimeType=null, array|int $options=[])

References $options.

◆ toDownload()

YAWK\SimpleImage::toDownload ( string  $filename,
string  $mimeType = null,
array|int  $options = 100 
)

Forces the image to be downloaded to the clients machine. Must be called before any output is sent to the screen.

Parameters
string$filenameThe filename (without path) to send to the client (e.g. 'image.jpeg').
string | null$mimeTypeThe image format to output as a mime type (defaults to the original mime type).
array | int$optionsArray or Image quality as a percentage (default 100).
Returns
SimpleImage
Exceptions
Exception

Definition at line 477 of file SimpleImage.php.

477  : static
478  {
479  $image = $this->generate($mimeType, $options);
480 
481  // Set download headers
482  header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
483  header('Content-Description: File Transfer');
484  header('Content-Length: '.strlen($image['data']));
485  header('Content-Transfer-Encoding: Binary');
486  header('Content-Type: application/octet-stream');
487  header("Content-Disposition: attachment; filename=\"$filename\"");
488 
489  echo $image['data'];
490 
491  return $this;
492  }

References $options.

◆ toFile()

YAWK\SimpleImage::toFile ( string  $file,
string  $mimeType = null,
array|int  $options = 100 
)

Writes the image to a file.

Parameters
string$fileThe image format to output as a mime type (defaults to the original mime type).
string | null$mimeTypeImage quality as a percentage (default 100).
array | int$optionsArray or Image quality as a percentage (default 100).
Returns
SimpleImage
Exceptions
ExceptionThrown if failed write to file.

Definition at line 504 of file SimpleImage.php.

504  : static
505  {
506  $image = $this->generate($mimeType, $options);
507 
508  // Save the image to file
509  if (! file_put_contents($file, $image['data'])) {
510  throw new Exception("Failed to write image to file: $file", self::ERR_WRITE);
511  }
512 
513  return $this;
514  }

References $options.

◆ toScreen()

YAWK\SimpleImage::toScreen ( string  $mimeType = null,
array|int  $options = 100 
)

Outputs the image to the screen. Must be called before any output is sent to the screen.

Parameters
string | null$mimeTypeThe image format to output as a mime type (defaults to the original mime type).
array | int$optionsArray or Image quality as a percentage (default 100).
Returns
SimpleImage
Exceptions
Exception

Definition at line 525 of file SimpleImage.php.

525  : static
526  {
527  $image = $this->generate($mimeType, $options);
528 
529  // Output the image to stdout
530  header('Content-Type: '.$image['mimeType']);
531  echo $image['data'];
532 
533  return $this;
534  }

References $options.

◆ toString()

YAWK\SimpleImage::toString ( string  $mimeType = null,
array|int  $options = 100 
)

Generates an image string.

Parameters
string | null$mimeTypeThe image format to output as a mime type (defaults to the original mime type).
array | int$optionsArray or Image quality as a percentage (default 100).
Exceptions
Exception

Definition at line 544 of file SimpleImage.php.

544  : string
545  {
546  return $this->generate($mimeType, $options)['data'];
547  }

References $options.

Member Data Documentation

◆ $exif

null array false YAWK\SimpleImage::$exif
protected

Definition at line 71 of file SimpleImage.php.

◆ $flags

array YAWK\SimpleImage::$flags
protected

Definition at line 65 of file SimpleImage.php.

◆ $image

YAWK\SimpleImage::$image
protected

Definition at line 67 of file SimpleImage.php.

◆ $mimeType

string YAWK\SimpleImage::$mimeType
protected

Definition at line 69 of file SimpleImage.php.

◆ ERR_FILE_NOT_FOUND

const YAWK\SimpleImage::ERR_FILE_NOT_FOUND = 1

Definition at line 30 of file SimpleImage.php.

◆ ERR_FONT_FILE

const YAWK\SimpleImage::ERR_FONT_FILE = 2

Definition at line 33 of file SimpleImage.php.

◆ ERR_FREETYPE_NOT_ENABLED

const YAWK\SimpleImage::ERR_FREETYPE_NOT_ENABLED = 3

Definition at line 36 of file SimpleImage.php.

◆ ERR_GD_NOT_ENABLED

const YAWK\SimpleImage::ERR_GD_NOT_ENABLED = 4

Definition at line 39 of file SimpleImage.php.

◆ ERR_INVALID_COLOR

const YAWK\SimpleImage::ERR_INVALID_COLOR = 5

Definition at line 42 of file SimpleImage.php.

◆ ERR_INVALID_DATA_URI

const YAWK\SimpleImage::ERR_INVALID_DATA_URI = 6

Definition at line 45 of file SimpleImage.php.

◆ ERR_INVALID_FLAG

const YAWK\SimpleImage::ERR_INVALID_FLAG = 12

Definition at line 63 of file SimpleImage.php.

◆ ERR_INVALID_IMAGE

const YAWK\SimpleImage::ERR_INVALID_IMAGE = 7

Definition at line 48 of file SimpleImage.php.

◆ ERR_LIB_NOT_LOADED

const YAWK\SimpleImage::ERR_LIB_NOT_LOADED = 8

Definition at line 51 of file SimpleImage.php.

◆ ERR_UNSUPPORTED_FORMAT

const YAWK\SimpleImage::ERR_UNSUPPORTED_FORMAT = 9

Definition at line 54 of file SimpleImage.php.

◆ ERR_WEBP_NOT_ENABLED

const YAWK\SimpleImage::ERR_WEBP_NOT_ENABLED = 10

Definition at line 57 of file SimpleImage.php.

◆ ERR_WRITE

const YAWK\SimpleImage::ERR_WRITE = 11

Definition at line 60 of file SimpleImage.php.


The documentation for this class was generated from the following file: