René Nyffenegger's collection of things on the web
René Nyffenegger on Oracle - Most wanted - Feedback -
 

Using Image::Magick with perl

Drawing a line

use Image::Magick;

my $image = Image::Magick->new;

$image -> Set(size=>"200x200");

$image -> ReadImage("xc:black");

$image -> Draw (
  stroke    => "red",
  primitive => "line",
  points    => "20,20 180,180");

$image -> write ("gif:line.gif");

Setting Pixels (by Drawing Mandelbrot images)

use Image::Magick;

my $width =300;
my $height=300;

my $image = Image::Magick->new;

$image -> Set(size=>"${width}x${width}");

$image -> ReadImage("xc:black");

$Cols   =$width; 
$Lines  =$height;
$MaxIter=255;
$MinRe  =-2.0; $MaxRe=1.0;
$MinIm  =-1.0; $MaxIm=1.0;
 
my $x=0;
for($Im=$MinIm;$Im<=$MaxIm;$Im+=($MaxIm-$MinIm)/$Lines) { 
  my $y=0;
  for($Re=$MinRe;$Re<=$MaxRe;$Re+=($MaxRe-$MinRe)/$Cols) { 
    $zr=$Re; $zi=$Im;
    for($n=0;$n<$MaxIter;$n++) { 

      $a=$zr*$zr; $b=$zi*$zi;

      last if($a+$b>4.0) ;

      $zi=2*$zr*$zi+$Im; 
      $zr=$a-$b+$Re;
    }

    my $hex=sprintf("#%02x%02x%02x", $n,$n,$n);
    
    $image -> Set ("pixel[$x,$y]"=>$hex);
    $y++;
  }
  $x++;
}


$image -> write ("gif:Mandelbrot.gif");

Iterating over available fonts and printing them

Note, this example runs on Windows and assumes the fontdirectory to be under c:\winnt\font.
use Image::Magick;

my $image = Image::Magick->new;

my $fontdir= 'c:\winnt\fonts';

opendir FONTDIR, $fontdir;
my $y=20;
my @fonts = grep /ttf$/, readdir FONTDIR;

$image -> Set (size=>"400x" . (scalar @fonts ) * 20);
$image -> ReadImage("xc:white");

for my $font (@fonts) { 
  $image -> Annotate(
    text     => $font, 
    stroke   =>"black", 
    fill     =>"blue", 
    x        =>5,
    y        =>$y, 
    pointsize=>14, 
    font     =>"\@$fontdir\\$font");

  $y+=20;
}

$image -> write ("gif:fonts.gif");