http://www.perlmonks.org?node_id=239968


in reply to Imager::Font examples

First, you'll need some true type library like Freetype or T1lib properly installed and Imager compiled to use it. You can check what libraries you've got using this snippet (from Image::Font's POD)
use Imager; print "Has truetype" if $Imager::formats{tt}; print "Has t1 postscript" if $Imager::formats{t1}; print "Has Win32 fonts" if $Imager::formats{w32}; print "Has Freetype2" if $Imager::formats{ft2};

And than, do something like

#!/usr/bin/perl -w use strict; use Imager; use Imager::Font; use Imager::Color; my $font_file='path/to/font.ttf'; my $text="Foo Bar!"; # create image my $img=Imager->new(xsize=>200,ysize=>50); # set colors my $white=Imager::Color->new("#ffffff"); my $black=Imager::Color->new("#000000"); # change background to white $img->box(color=>$white,filled=>1); # create font object my $ttfont=Imager::Font->new ( type=>'ft2', file=>$font_file, color=>$black, size=>16, ); # draw text $img->string(font=>$ttfont,text=>$text, x=>5,y=>22,aa=>1); # write file $img->write(file=>"image.png") or die "Cannot write $imgfn: ", $img->errstr;
Hope this helps!
-- #!/usr/bin/perl for(ref bless{},just'another'perl'hacker){s-:+-$"-g&&print$_.$/}

Replies are listed 'Best First'.
Re: Imager::Font examples
by neilwatson (Priest) on Mar 03, 2003 at 15:30 UTC
    Thanks. A couple of questions:

    How would you determine the size of the image file automatically, if the font size was dynamic, without reserving a large image size?

    How do I send the image to a web browser without saving the file first?

    Neil Watson
    watson-wilson.ca

      How would you determine the size of the image file automatically, if the font size was dynamic, without reserving a large image size?

      Hmm, never done that. One idea: Generate a very large image, draw the text, use $font->bounding_box to get the dimensions of the drawn string, and finally crop the image accordingly.

      How do I send the image to a web browser without saving the file first?

      Try something like this:

      my $img_data; $img->write(data=>\$img_data,type=>'png') or die "Cannot dump image: ", $img->errstr;

      Now you've got the image in $img_data, so you can print it to STDOUT (or via CGI). If operating under CGI, don't forget to set the proper content-type.

      -- #!/usr/bin/perl for(ref bless{},just'another'perl'hacker){s-:+-$"-g&&print$_.$/}