Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if file is an image in perl

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?

like image 303
Thariama Avatar asked Jun 18 '12 12:06

Thariama


3 Answers

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).

like image 134
Eric Redon Avatar answered Nov 15 '22 18:11

Eric Redon


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.

like image 27
daxim Avatar answered Nov 15 '22 18:11

daxim


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.

like image 3
sjsperry Avatar answered Nov 15 '22 18:11

sjsperry