使用Perl Imager库扩展字体

时间:2013-03-19 13:48:24

标签: perl fonts scaling

我正在编写一个脚本,使用Imager和Imager :: Font和ft2库。该脚本尝试确定以给定字体呈现的字符串是否将超过图像的宽度,如果是,则缩小字体以使其适合图像内部。但是,它并没有像我期望的那样工作。测试脚本显示在下方,以便您可以尝试自己复制结果。最终发生的事情是,按比例缩小的字体中的字符串看起来占据与原始字体大致相同的宽度,并从左侧大致相同的点开始。这意味着当它变小时,弦线会从图像的左侧进一步移动,直到它完全不可见为止。

有关如何解决此问题的任何建议吗?

谢谢,

彼得

下面的

脚本:

#!/usr/local/bin/perl

# imager_scaling_test
#
# This is a script designed to test whether we can
# dynamically scale a font down so that it fits within
# the width of an image. This is designed to be run
# under mod_perl and viewed in a web browser.
#
# Test examples:
#
# This works fine:
# imager_scaling_test?string=TEST
#
# This produces output that goes partially outside of the box
# imager_scaling_test?string=TESTTTTTTTTTTTTT
#
# This produces output that is completely outside of the box
# imager_scaling_test?string=TESTTTTTTTTTTTTTTTTTTTTTTTTTTT

use strict;
use Apache;
use CGI;
use Imager;
use Imager::Font;

my $r = Apache->request;
my $q = CGI->new();

# Some variables to control our test
my $string       = $q->param( 'string' ) || 'TEST';
my $image_width  = 400;
my $image_height = 400;
my $font_size    = 70;
my $font_file    = 'your_font.ttf';

# Create a basic imager object to work in
my $image = Imager->new( xsize => $image_width, ysize => $image_height );

# Create a box on the image
$image->box(
    xmin   => 0,
    xmin   => 0,
    xmax   => $image_width - 1,
    ymax   => $image_height - 1,
    filled => 1,
    color  => 'blue'
);

# Set up the font
my $font = Imager::Font->new( file => $font_file, size => $font_size );

# Find out how wide our test string would be in this font
my $bbox1 = $font->bounding_box( string => $string );
my $initial_width = $bbox1->display_width();
$r->log_error( "Initial width:$initial_width" );

# Find out whether the test string is wider than the image
if ( $initial_width > $image_width ) {

    # Find the difference between the string width and the image width
    my $difference = $initial_width - $image_width;

    # Find the percentage the image width is of the initial width
    my $percentage = $image_width / $initial_width;

    # Set up a scaling matrix to scale the font
    my $scaling_matrix = [ $percentage, 0, 0, 0, $percentage, 0 ];
    $font->transform( matrix => $scaling_matrix );
    my $bbox2 = $font->bounding_box( string => $string );
    my $scaled_width = $bbox2->display_width();
    $r->log_error( "Scaled width:$scaled_width" );
}

# Place the string on the image
$image->align_string(
    valign => 'center',
    halign => 'center',
    font   => $font,
    x      => $image->getwidth / 2,
    y      => $image->getheight / 2,
    text   => $string,
);

# Print the image out to the browser.
my $output;
$image->write( type => 'jpeg', data => \$output );
binmode STDOUT;
$r->content_type( "image/jpeg" );
$r->send_http_header;
$r->print( $output );

0 个答案:

没有答案
相关问题