I wanted to find the type of an image as a part of upload script I am working on.

instead of having to use a module that is not pre-installed with perl or a module that requires some libraries to be installed on the server, I used this method.

sub imgtype { my $file = shift; my %types = ( 'BMP' => qr/^BM/, 'GIF' => qr/^GIF8[79]a/, 'JPEG' => qr/^\xFF\xD8/, 'PNG' => qr/^\x89PNG\x0d\x0a\x1a\x0a/, 'PPM' => qr/^P[1-6]/, 'SVG' => qr/^<\?xml/, 'TIFF' => qr/^MM\x00\x2a|^II\x2a\x00/, 'XBM' => qr/^#define\s+/, 'XPM' => qr/(^\/\* XPM \*\/)|(static\s+char\s+\*\w+\[\]\s*= +\s*{\s*"\d+)/, ); if (-e $file ) { open(my $fh, '<', $file) or die $!; read($fh,my $head,11); close($fh); while ( my ($type,$match) = each %types ) { if ( $head=~m/$match/ ) { return $type; } } return undef; }else{ return undef; } }

You can use it to check against a hash of allowed file types like this

my %ALLOWED = ('GIF' => 1 ,'JPEG' => 1 ); # can be called like this my $Type = imgtype('some/location/image'); if ( defined $Type && $ALLOWED{$Type} ) { # process image }else{ # delete it or do whatever you want with it }

In reply to How do I find the type of an image? by ahmad

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.