From 42d808bd61834620b0408716dc93f03d65367768 Mon Sep 17 00:00:00 2001 From: Tom Witkowski Date: Thu, 14 Sep 2017 15:42:58 +0200 Subject: [PATCH 1/2] add getBoxSize() for imagick In addition to #165 it would be great if `imagick` also supports this method. --- src/Intervention/Image/Imagick/Font.php | 40 +++++++++++++++++++++++++ 1 file changed, 40 insertions(+) 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; + } } From 240e08c13a7b407ed31f3eb54f15b1b4892d6c7a Mon Sep 17 00:00:00 2001 From: Tom Witkowski Date: Thu, 14 Sep 2017 15:44:08 +0200 Subject: [PATCH 2/2] add getBoxSize() as abstract method --- src/Intervention/Image/AbstractFont.php | 7 +++++++ 1 file changed, 7 insertions(+) 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