measuring string size for Annotate()

PerlMagick is an object-oriented Perl interface to ImageMagick. Use this forum to discuss, make suggestions about, or report bugs concerning PerlMagick.
Post Reply
danmc
Posts: 8
Joined: 2014-09-08T18:18:38-07:00
Authentication code: 6789

measuring string size for Annotate()

Post by danmc » 2014-09-11T13:23:30-07:00

Is there a way to figure out if text added via Annotate() got cut off when added to a background of a fixed size? Alternatively is there a way to figure out how much room will be needed for text? I have something like the following but in some cases the string stored in $names is too big and I either need to automatically adjust the font size or at least log a warning at the program output.

Thanks
-Dan

Code: Select all

my $text_back = Image::Magick->new();
my $x = $text_back->ReadImage('xc:white');
warn "$x" if "$x";

my $my_h = 150;
my $my_w = 600;

print "[$my_w x $my_h] ...";
$text_back->Resize(width=>$my_w, height=>$my_h);

# code here to read $names out of a file.  It may be
# a couple of lines long

print "Adding label...";
$text_back->Annotate(undercolor=>'white',
                       font=>'LCALLIG.TTF',
                       pointsize=>36,
                       fill=>'black',
                       gravity=>'Center',
                       text=>$names);

User avatar
fmw42
Posts: 25408
Joined: 2007-07-02T17:14:51-07:00
Authentication code: 1152
Location: Sunnyvale, California, USA

Re: measuring string size for Annotate()

Post by fmw42 » 2014-09-11T14:00:06-07:00


snibgo
Posts: 12011
Joined: 2010-01-23T23:01:33-07:00
Authentication code: 1151
Location: England, UK

Re: measuring string size for Annotate()

Post by snibgo » 2014-09-11T14:33:12-07:00

My general technique for this is to annotate to an area larger than required, and see if that larger area was needed. (In most cases, this means trimming it, and ensuring this is smaller in both dimensions than the required area.)
snibgo's IM pages: im.snibgo.com

danmc
Posts: 8
Joined: 2014-09-08T18:18:38-07:00
Authentication code: 6789

Re: measuring string size for Annotate()

Post by danmc » 2014-09-13T08:59:37-07:00

This seemed to do the trick. Then I was able to scale the font, if needed, for the Annotate() call.

Code: Select all


  print "Checking label size...";
  my ($x_ppem, $y_ppem, $ascender, $descender, $width, $height, $max_advance)
    = $text_back->QueryMultilineFontMetrics(
                                            undercolor=>'white',
                                            font=>$font_file,
                                            pointsize=>$font_size, 
                                            fill=>'black', 
                                            gravity=>'Center',
                                            text=>$names
                                           );
  print "[$width x $height] vs [$my_w x $my_h]...";



Post Reply