Angel has asked for the wisdom of the Perl Monks concerning the following question:

This is probaly elementary but I dont know how to generate an image dynamically and then send it to the user. I can generate images using GD and Image Magik and save them on the server and then link to them with HTML but that wont work in this case. How do I do that?
  • Comment on How to get Dynamic Images on the Screen

Replies are listed 'Best First'.
•Re: How to get Dynamic Images on the Screen
by merlyn (Sage) on Jun 09, 2002 at 16:04 UTC
    If you have no HTML around it, and just want to send back the image as the response to the URL, just generate it and send the right header, like Content-type: image/jpeg for a JPEG. (Aside: Be sure to put the space after the colon: far too many web examples and code posted here leaves it out, and that breaks things.)

    If you want the image embedded into the rest of an output HTML page, I have a column on that, so you can use that as a starting point.

    -- Randal L. Schwartz, Perl hacker

Re: How to get Dynamic Images on the Screen
by dree (Monsignor) on Jun 09, 2002 at 16:07 UTC
    You have to print the image to the standard output, but before you have to put this 2 instructions:

    1) binmode STDOUT;
    2) print "Content-type img/png\n\n"; "Content-type: image/png\n\n"; #as merlyn said

    The GD example becomes:
    use GD; # create a new image $im = new GD::Image(100,100); # allocate some colors $white = $im->colorAllocate(255,255,255); $black = $im->colorAllocate(0,0,0); $red = $im->colorAllocate(255,0,0); $blue = $im->colorAllocate(0,0,255); # make the background transparent and interlaced $im->transparent($white); $im->interlaced('true'); # Put a black frame around the picture $im->rectangle(0,0,99,99,$black); # Draw a blue oval $im->arc(50,50,95,75,0,360,$blue); # And fill it with red $im->fill(50,50,$red); # make sure we are writing to a binary stream binmode STDOUT; print "Content-type: image/png\n\n"; #as [merlyn] said # Convert the image to PNG and print it on standard output print $im->png;

    UPDATE: fixed the error in the content type string

Re: How to get Dynamic Images on the Screen
by boo_radley (Parson) on Jun 09, 2002 at 16:11 UTC
    A common way to provide dynamic images is to write a script that will output a png|jpg and then place that in an image tag: <img src="example_img_generator.pl">.
    Be sure to binmode STDOUT if you're on windows (and it doesn't impact anything if you're on a different os) and to print out the appropriate content type header (and any other http header you may require and you should be good to go.