In order to set some varaibles i need the information if a given file on my server is an image. I do not know anything about the file exept for its location and name.
Is there a way to detect if a file is an image WITHOUT looking at the file extension?
An easy way to do this is to delegate the work to ImageMagick through the PerlMagick CPAN module. The Identify
and Ping
methods are designed for that purpose.
use strict;
use Image::Magick;
my $im = Image::Magick->new();
my ($width, $height, $size, $format) = $im->Ping('/path/to/my/image.jpg');
After executing this little program, the $format
variable will contain a string with the identified format of the image (in this example: "JPEG"), or undef
in case of error (non-existing file, unrecognized format, etc.).
Edit: ...and to completely answer your question: it is probably safe to assume that a given file is an image if Ping
returns a format string, and if it is part of whichever subset you decide to white-list from ImageMagick's list of supported formats (which also includes non-image formats).
JRFerguson mentions the command file
in a comment attached to the question. It comes with a C library counter-part, libmagic
. The Perl binding is called File::LibMagic.
use File::LibMagic qw();
my $detect = File::LibMagic->new;
$detect->checktype_filename("first_success.jpg") =~ /^image/
Expression returns true for image types.
The command file
, as first mentioned by @JRFerguson, has limitations versus File::LibMagic
, Image::Magick
, or Image::ExifTool
.
But file
is great when you can't install or use those modules. As for sample code, you could go with something like this:
my $file = "/dir/images/image.jpg";
my $type = `file $file`;
unless ($type =~ /JPEG/i
|| $type =~ /PNG/i) {
print "The file is not a valid JPEG or PNG.";
}
The idea is just to regex against the known image formats.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With