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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |