⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch13_05.htm

📁 用perl编写CGI的好书。本书从解释CGI和底层HTTP协议如何工作开始
💻 HTM
📖 第 1 页 / 共 2 页
字号:
<?label 13.5. PerlMagick?><html><head><title>PerlMagick (CGI Programming with Perl)</title><link href="../style/style1.css" type="text/css" rel="stylesheet" /><meta name="DC.Creator" content="Scott Guelich, Gunther Birznieks and Shishir Gundavaram" /><meta scheme="MIME" content="text/xml" name="DC.Format" /><meta content="en-US" name="DC.Language" /><meta content="O'Reilly & Associates, Inc." name="DC.Publisher" /><meta scheme="ISBN" name="DC.Source" content="1565924193L" /><meta name="DC.Subject.Keyword" content="stuff" /><meta name="DC.Title" content="CGI Programming with Perl" /><meta content="Text.Monograph" name="DC.Type" /></head><body bgcolor="#ffffff"><img src="gifs/smbanner.gif" alt="Book Home" usemap="#banner-map" border="0" /><map name="banner-map"><area alt="CGI Programming with Perl" href="index.htm" coords="0,0,466,65" shape="rect" /><area alt="Search this book" href="jobjects/fsearch.htm" coords="467,0,514,18" shape="rect" /></map><div class="navbar"><table border="0" width="515"><tr><td width="172" valign="top" align="left"><a href="ch13_04.htm"><img src="../gifs/txtpreva.gif" alt="Previous" border="0" /></a></td><td width="171" valign="top" align="center"><a href="index.htm">CGI Programming with Perl</a></td><td width="172" valign="top" align="right"><a href="ch14_01.htm"><img src="../gifs/txtnexta.gif" alt="Next" border="0" /></a></td></tr></table></div><hr align="left" width="515" /><h2 class="sect1">13.5. PerlMagick</h2><p><a name="INDEX-2643" /><a name="INDEX-2644" />PerlMagick is another graphics moduledesigned to be used online. It is based upon the<a name="INDEX-2645" />ImageMagick library, <a name="INDEX-2,646" /> <a name="INDEX-2,647" /> <a name="INDEX-2,648" />which is available for many languages onmany different platforms. The Perl module, Image::Magick, is oftenreferred to as PerlMagick. ImageMagick was written by John Cristy;the Perl module was written by Kyle Shorter.</p><p>ImageMagick is very powerful and supports the following operations:</p><dl><dt><b><em class="emphasis">Identify</em></b></dt><dd><p>ImageMagick supports more than fifty different image file formats,including GIF, JPEG, PNG, TIFF, BMP, EPS, PDF, MPEG, PICT, PPM, andRGB.</p></dd><dt><b><em class="emphasis">Convert</em></b></dt><dd><p>ImageMagick allows you to convert between these formats.</p></dd><dt><b><em class="emphasis">Montage</em></b></dt><dd><p>ImageMagick can create thumbnails of images.</p></dd><dt><b><em class="emphasis">Mogrify</em></b></dt><dd><p>ImageMagick can perform all sorts of manipulations on imagesincluding blur, rotate, emboss, and normalize, just to name a few.</p></dd><dt><b><em class="emphasis">Drawing</em></b></dt><dd><p>Like GD, you can add basic shapes and text to images in ImageMagick.</p></dd><dt><b><em class="emphasis">Composite</em></b></dt><dd><p>ImageMagick can merge multiple images.</p></dd><dt><b><em class="emphasis">Animate</em></b></dt><dd><p>ImageMagick supports file formats with multiple frames, such asanimated GIFs.</p></dd><dt><b><em class="emphasis">Display</em></b></dt><dd><p>ImageMagick also includes tools, such as <tt class="command">display</tt>,for displaying and manipulating images interactively.</p></dd></dl><p>We won't cover all of these, of course. We'll look at howto convert between different formats as well as how to create animage using some of the advanced effects.</p><a name="ch13-17-fm2xml" /><div class="sect2"><h3 class="sect2">13.5.1. Installation</h3><p>You can obtain the Image::Magick module from CPAN, but it requiresthat the <a name="INDEX-2649" /><a name="INDEX-2650" />ImageMagick library be installedalready. You can get ImageMagick from the ImageMagick home page,<a href="http://www.wizards.dupont.com/cristy/">http://www.wizards.dupont.com/cristy/</a>. Thispage contains links to many resources, including pre-compiled binarydistributions of ImageMagick for many operating systems, detailedbuild instructions if you choose to compile it yourself, and adetailed PDF manual.</p><a name="ch13-18-fm2xml" /><div class="sect3"><h3 class="sect3">13.5.1.1. Requirements</h3><p>Image::Magick is much <a name="INDEX-2651" /> <a name="INDEX-2,652" />morepowerful than GD. It supports numerous file formats and allows manytypes of operations, while GD is optimized for a certain set of tasksand a single file format. However, this power comes at a price.Whereas the GD module has relatively low overhead and is quiteefficient, the Image::Magick module may crash unless it has at least80MB of memory, and for best performance at least 64MB should be realRAM (i.e., not virtual memory).</p></div><a name="ch13-19-fm2xml" /><div class="sect3"><h3 class="sect3">13.5.1.2. Enabling LZW compression</h3><p>Image::Magick <a name="INDEX-2653" /> <a name="INDEX-2,654" />supports GIFs. However, <a name="INDEX-2,655" /> <a name="INDEX-2,656" />support for LZW compression is notcompiled into ImageMagick by default. This causes GIFs that arecreated by Image::Magick to be quite large. It is possible to enableLZW compression when building ImageMagick, but of course you shouldcheck with Unisys about licensing and/or contact an attorney beforedoing so. Refer to the ImageMagick build instructions for moreinformation.</p></div></div><a name="ch13-20-fm2xml" /><div class="sect2"><h3 class="sect2">13.5.2. Converting PNGs to GIFs or JPEGs</h3><p>As we noted <a name="INDEX-2657" /> <a name="INDEX-2,658" />earlier, unfortunately not all browserssupport PNGs. Let's see how we can use Image::Magick to converta PNG to a GIF or a JPEG. In order to use an image in Image::Magick,you must read it from a file. According to the documentation, itshould also accept input from a file handle, but as of the time thisbook was written, this feature is broken (it silently fails). We willthus write the output of GD to a temporary file and then read it backin to Image::Magick. <a href="ch13_05.htm#ch13-37219">Example 13-5</a> includes ourearlier example, <em class="filename">commute_pie.cgi</em><a name="INDEX-2659" />, updated to output<a name="INDEX-2660" />a JPEG instead unless the browserspecifically states that it supports PNG files.</p><a name="ch13-37219" /><div class="example"><h4 class="objtitle">Example 13-5. commute_pie2.cgi </h4><blockquote><pre class="code">#!/usr/bin/perl -wTuse strict;use CGI;use GD::Graph::pie;use Image::Magick;use POSIX qw( tmpnam );use Fcntl;use constant TITLE =&gt; "Average Commute Time: Pie Chart";my $q     = new CGI;my $graph = new GD::Graph::pie( 300, 300 );my @data  = (    [ qw( Mon  Tue  Wed  Thu  Fri ) ],    [      33,  24,  23,  19,  21   ],    [      17,  15,  19,  15,  24   ],);$graph-&gt;set(     title           =&gt; TITLE,    '3d'            =&gt; 0);my $gd_image = $graph-&gt;plot( \@data );undef $graph;if ( grep $_ eq "image/png", $q-&gt;Accept )    print $q-&gt;header( -type =&gt; "image/png", -expires =&gt; "now" );    binmode STDOUT;    print $gd_image-&gt;png;}else {    print $q-&gt;header( -type =&gt; "image/jpeg", -expires =&gt; "now" );    binmode STDOUT;    print_png2jpeg( $gd_image-&gt;png );}# Takes PNG data, converts it to JPEG, and prints itsub print_png2jpeg {    my $png_data = shift;    my( $tmp_name, $status );        # Create temp file and write PNG to it    do {        $tmp_name = tmpnam(  );    } until sysopen TMPFILE, $tmp_name, O_RDWR | O_CREAT | O_EXCL;    END { unlink $tmp_name or die "Cannot remove $tmp_name: $!"; }        binmode TMPFILE;    print TMPFILE $png_data;    seek TMPFILE, 0, 0;    close TMPFILE;    undef $png_data;        # Read file into Image::Magick    my $magick = new Image::Magick( format =&gt; "png" );    $status = $magick-&gt;Read( filename =&gt; $tmp_name );    warn "Error reading PNG input: $status" if $status;        # Write file as JPEG to STDOUT    $status = $magick-&gt;Write( "jpeg:-" );    warn "Error writing JPEG output: $status" if $status;}</pre></blockquote></div><p>We use a few more modules in this script, including Image::Magick,POSIX, and Fcntl. The latter two allow us to get a temporaryfilename. See <a href="ch10_01.htm#ch10-92014">Section 10.1.3, "Temporary Files"</a>. The only other change tothe main body of our script is a check for the<em class="emphasis">image/png</em> media type in the browser's<em class="emphasis">Accept</em><a name="INDEX-2661" /> <a name="INDEX-2,662" /> header. If it exists, we send the PNG asis. Otherwise, we output a header for a JPEG and use the<tt class="function">print_png2jpeg</tt> function to convert and outputthe image.</p><p>The <tt class="function">print_png2jpeg</tt> function takes PNG imagedata, creates a named temporary file, and writes the PNG data to it.Then it closes the file and discards its copy of the PNG data inorder to conserve a little extra memory. Then we create anImage::Magick object and read the PNG data from our temporary fileand write it back out to STDOUT in JPEG format. Image::Magick usesthe<tt class="literal">format:filename</tt><a name="INDEX-2663" /> string for the<tt class="function">Write</tt> method, and using <tt class="literal">-</tt>instead of <tt class="literal">filename</tt> indicates that it<a name="INDEX-2664" />should write to STDOUT. We could outputthe data as a <a name="INDEX-2665" />GIF by changing our output header and usingthe following <em class="emphasis">Write</em> command instead:</p><blockquote><pre class="code">$status = $magick-&gt;Write( "gif:-" );</pre></blockquote><p>Image::Magick returns a<a name="INDEX-2666" />status with everymethod call. Thus <tt class="literal">$status</tt> is set if an erroroccurs, which we log with the <tt class="function">warn</tt> function.</p><p>There is a trade-off to not using PNG. Remember that a GIF produced

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -