You are right with your guess that instead of writing to the "STDOUT" of the Mason component, your $image->Write('png:-') call writes the image somewhere else.

I suppose that this is a mod_perl limitation. Are you running Mason under mod_perl?
In a terminal program or with CGI both commands "print $header_templ" and "system('cat /my/templates/header.html')" will write to the same "STDOUT", but under mod_perl this is not so.

You have two options

  1. Use Mason handler as CGI Script, in this case the following code works
    <%flags> inherit => undef </%flags> <%init> use Image::Magick; my $image = Image::Magick->new; $image->Set(size => '500 x 750'); $image->Read('xc:black'); STDOUT->autoflush(1); $r->content_type('image/png'); $r->send_http_header; $image->Write("png:-"); </%init>
  2. Unfortunately Image::Magick can't write to scalar or filehandle. So let Image::Magick to write the image to some tempfile, then open this tempfile again, read it into a scalar and print to STDOUT, or use the "$r->sendfile" method from mod_perl like this.
    <%flags> inherit => undef </%flags> <%init> use Image::Magick; use File::Temp; my $image = Image::Magick->new; $image->Set(size => '500 x 750'); $image->Read('xc:green'); my $temp = File::Temp->new( DIR => '/tmp', UNLINK => 1); my $temp_file_name = $temp->filename; $image->Write("png:$temp_file_name"); $r->content_type('image/png'); $r->sendfile($temp_file_name); # File::Slurp and print could be used instead of $r->sendfile # #use File::Slurp; #print read_file($temp_file_name); </%init>


In reply to Re: Image::Magick in Mason and STDOUT by nif
in thread Image::Magick in Mason and STDOUT by eugeneman42

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.