user11223077
user11223077

Reputation:

Creating an image with text using Perl's Image::Magick

I am working on some examples for a lunch-n-learn talking about HTTP context headers and some of the things they are used for. I figured to add some flare into things, to create an image with Perl's Image::Magick.

Thanks to a comment on this original post I have learned the problem is a missing Content-Length. How do I get the correct context length from the image?

P.S. I tweaked the Content-Type to make type capital.

#!/perl/bin/perl.exe

use Image::Magick;

$image = Image::Magick->new;
$image->Set(size=>'100x100');
$image->ReadImage('canvas:white');
$image->Set('pixel[49,49]'=>'red');

$text = 'Works like magick!';
$image->Annotate(font=>'kai.ttf', pointsize=>40, fill=>'green', text=>$text);

print "Content-Type: image/png\n\n";
binmode STDOUT;
$image->Write('png:-');

Upvotes: 1

Views: 932

Answers (1)

k-mx
k-mx

Reputation: 687

Why not Mojolicious (An amazing real-time web framework)?

use Mojolicious::Lite;

use Image::Magick;

get '/' => sub {
  my $c = shift;

  ...

  $c->render( data => $image->ImageToBlob( magick => 'png' ), format => 'png' );
};

app->start;

run it with perl my_script.pl daemon

And open in browser localhost:3000

Or fix for original code:

#!/usr/bin/env perl

use strict;
use warnings;

use Image::Magick;

my $image = Image::Magick->new;
$image->Set( size => '200x200' );
$image->ReadImage( 'canvas:white' );
$image->Set( 'pixel[49,49]' => 'red' );

$image->Annotate(
    font      => 'kai.ttf',
    pointsize => 22,
    fill      => 'green',
    text      => 'Works like magick!',
    gravity   => 'northwest',
);

my $img_size;
my $img_data = $image->ImageToBlob( magick => 'png' );

{
    use bytes;
    $img_size = length $img_data;
}

binmode STDOUT;
print <<EOD;
Content-Type: image/png
Content-Length: $img_size

$img_data
EOD

Upvotes: 2

Related Questions