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 }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: How do I find the type of an image?
by JavaFan (Canon) on Dec 28, 2009 at 13:11 UTC | |
by zentara (Cardinal) on Dec 28, 2009 at 13:18 UTC | |
|
Re: How do I find the type of an image?
by ahmad (Hermit) on Dec 28, 2009 at 15:55 UTC | |
by zentara (Cardinal) on Dec 28, 2009 at 16:41 UTC | |
by ahmad (Hermit) on Dec 29, 2009 at 02:05 UTC | |
by zentara (Cardinal) on Dec 29, 2009 at 12:29 UTC | |
by Anonymous Monk on Dec 29, 2009 at 13:23 UTC | |
| |
by ahmad (Hermit) on Dec 29, 2009 at 14:42 UTC | |
| |
by JavaFan (Canon) on Dec 29, 2009 at 23:41 UTC | |
by matze77 (Friar) on Dec 30, 2009 at 10:56 UTC | |
|
Re: How do I find the type of an image?
by doug (Pilgrim) on Dec 28, 2009 at 17:14 UTC |