Skip to content

Instantly share code, notes, and snippets.

@AydinHassan
Created December 7, 2015 15:29
Show Gist options
  • Save AydinHassan/f64b2b5f45715da8478c to your computer and use it in GitHub Desktop.
Save AydinHassan/f64b2b5f45715da8478c to your computer and use it in GitHub Desktop.
<?php
namespace Hft\Font;
/**
* Class ImageTtfBbox
* @package Hft\Font
* @author Aydin Hassan <[email protected]>
*/
class Image
{
/**
* @param int $size
* @param int $angle
* @param string $font
* @param string $text
*
* @return array
*/
public function imagettfbbox($size, $angle, $font, $text)
{
$dimensions = imagettfbbox($size, $angle, $font, $text);
$width = abs($dimensions[4] - $dimensions[0]);
$height = abs($dimensions[5] - $dimensions[1]);
$exaggeratedWidth = $width * 2;
$exaggeratedHeight = $height * 2;
$image = imagecreatetruecolor($exaggeratedWidth, $exaggeratedHeight);
$fontColour = imagecolorallocate($image, 0, 0, 0); //000000
$bgColour = imagecolorallocate($image, 204, 204, 204); //CCCCCC
imagefilledrectangle($image, 0, 0, $exaggeratedWidth, $exaggeratedHeight, $bgColour);
$x1 = $dimensions[0] + ($width / 2);
$y1 = $dimensions[7] + $height;
$x2 = $dimensions[2] + ($width / 2);
$y2 = $dimensions[3] + $height;
imagefilledrectangle($image, $x1, $y1, $x2, $y2, imagecolorallocate($image, 255, 255, 255));
imagettftext($image, $size, $angle, $width / 2, $height, $fontColour, $font, $text);
$xOffset = $this->getXOffset($image, $x1, $y1, $width, $height);
return [
-$xOffset,
$dimensions[1],
$dimensions[2] - $xOffset,
$dimensions[3],
$dimensions[4] - $xOffset,
$dimensions[5],
-$xOffset,
$dimensions[7]
];
}
/**
* @param resource $image
* @param int $xStart
* @param int $yStart
* @param int $width
* @param int $height
*
* @return int
*/
private function getXOffset($image, $xStart, $yStart, $width, $height)
{
$rgbWhite = [255, 255, 255];
$xRight = $xStart + $width;
$yBottom = $yStart + $height;
for ($x = $xRight; $x >= $xStart; $x--) {
for ($y = $yBottom; $y >= $yStart; $y--) {
$pixelColour = imagecolorat($image, $x, $y);
if ($this->indexToRgb($pixelColour) !== $rgbWhite) {
return ($width + $xStart) - $x;
}
}
}
return 0;
}
/**
* @param int $index
* @return array
*/
private function indexToRgb($index)
{
$r = ($index >> 16) & 0xFF;
$g = ($index >> 8) & 0xFF;
$b = $index & 0xFF;
return [$r, $g, $b];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment