I wanted a simple script that displays the dimensions of a given image file so that i could create HTML <img> tags a bit easier when i design web pages. Image::Size is a really handy module for doing just this, and while i could always use a one-liner like:
but i wanted something more flexible. The original was much shorter than this, but i feel if you are going to share code, make it robust, and use tools such as Getopt::Long and Pod::Usage, which always take up room ... but some people really like to have documentation and "social engineering". ;)perl -MImage::Size -le"print for imgsize shift" foo.png
See Image Xs and Ys and Image size in pure perl for similar nodes.
#!/usr/bin/perl -l use strict; use warnings; use Pod::Usage; use Getopt::Long; use CGI qw(img); use File::Basename; use Image::Size qw(html_imgsize attr_imgsize); # "register" more extensions here ---V our @EXT = map {$_,uc($_)} qw(.gif .jpg .png); our (@file,$dir,$html,$help); if ($ARGV[0] and -e $ARGV[0]) { ($html,@file) = @ARGV[1,0]; } else { get_options(); } for (map {glob} @file) { next unless (fileparse($_,@EXT))[2]; if ($html) { print img({ -src => basename($_), -alt => basename($_,@EXT), attr_imgsize($_) }); } else { print "$_: ", html_imgsize($_); } } sub get_options { GetOptions( 'file|f=s' => \@file, 'dir|d=s' => \$dir, 'html' => \$html, 'help|h|?' => \$help, ); pod2usage(-verbose=>2) if $help; pod2usage(-verbose=>1) unless @file or $dir; if ($dir) { @file = map glob("$dir/*$_"), @EXT; } } __END__ =head1 NAME img - print dimensions for (web) image files =head1 SYNOPSIS img -file [-dir -html -help] Options: -file -f file to read, can list multiple -dir -d directory to read from -html print as HTML img tag -help -h -? brief help message =head1 DESCRIPTION B<This program> uses Image::Size to display the dimensions of the specified image file(s). The program defaults to servicing GIF, PNG, and JPEG images file, if you wish to add more extensions, simply add them to the list at the right of the assignment to @EXT (look for the comment). Also, i opted to add "canned" src and alt tags when printing in HTML img mode. Feel free to change this code to suite your needs. =head1 EXAMPLES Print size of single file: img -file foo.jpg img -f foo.jpg img foo.jpg Print HTML img tag from single file: img -file foo.jpg -html img -f foo.jpg -html img foo.jpg -html Multiple files: img -file=foo.jpg -file=bar.jpg img -file=foo.jpg -file=bar.jpg -html Glob: img -file=*.jpg img -file=*.jpg -html img -file=*.jpg -file=*.png img -file=*.jpg -file=*.png -html (caveat) img -f=* (this prints all files) img -f * (this only gets first match) All "registered" images in a directory: img -dir images img -d images img -d images -html =head1 AUTHOR jeffa F<http://www.perlmonks.org/?node_id=18800> This code can be found online at F<http://www.perlmonks.org/?node_id=295108> =cut
|
|---|