diff --git a/src/Intervention/Image/AbstractFont.php b/src/Intervention/Image/AbstractFont.php index 8bcf3b28..cdc690f3 100644 --- a/src/Intervention/Image/AbstractFont.php +++ b/src/Intervention/Image/AbstractFont.php @@ -62,6 +62,13 @@ abstract class AbstractFont * @return boolean */ abstract public function applyToImage(Image $image, $posx = 0, $posy = 0); + + /** + * Calculates bounding box of current font setting + * + * @return array + */ + abstract public function getBoxSize(); /** * Create a new instance of Font diff --git a/src/Intervention/Image/Imagick/Font.php b/src/Intervention/Image/Imagick/Font.php index 9ae2f978..ee1eb328 100644 --- a/src/Intervention/Image/Imagick/Font.php +++ b/src/Intervention/Image/Imagick/Font.php @@ -75,4 +75,44 @@ class Font extends \Intervention\Image\AbstractFont // apply to image $image->getCore()->annotateImage($draw, $posx, $posy, $this->angle * (-1), $this->text); } + + /** + * Calculates bounding box of current font setting + * + * @return array + */ + public function getBoxSize() + { + $box = []; + + // build draw object + $draw = new \ImagickDraw(); + $draw->setStrokeAntialias(true); + $draw->setTextAntialias(true); + + // set font file + if ($this->hasApplicableFontFile()) { + $draw->setFont($this->file); + } else { + throw new \Intervention\Image\Exception\RuntimeException( + "Font file must be provided to apply text to image." + ); + } + + $draw->setFontSize($this->size); + + $dimensions = (new \Imagick())->queryFontMetrics($draw, $this->text); + + if (strlen($this->text) == 0) { + // no text -> no boxsize + $box['width'] = 0; + $box['height'] = 0; + } else { + // get boxsize + $box['width'] = intval(abs($dimensions['textWidth'])); + $box['height'] = intval(abs($dimensions['textHeight'])); + } + + return $box; + } }