How to determine if a file is an image in perl

To set some variables, I need information if the given file on my server is an image. I do not know anything about the file except its location and name.

Is there a way to determine if a file is an image WITHOUT viewing the file extension?

+5
source share
5 answers

An easy way to do this is to transfer ImageMagick work through the PerlMagick CPAN module. For this purpose, methods Identifyand have been developed Ping.

use strict;
use Image::Magick;

my $im = Image::Magick->new();

my ($width, $height, $size, $format) = $im->Ping('/path/to/my/image.jpg');

$format ( : "JPEG" ) undef ( , ..).

:... : , , , Ping , , ImageMagick ( ).

+10

JRFerguson file , . - C, libmagic. Perl File::LibMagic.

use File::LibMagic qw();
my $detect = File::LibMagic->new;
$detect->checktype_filename("first_success.jpg") =~ /^image/

true .

+8

file, @JRFerguson, File::LibMagic, Image::Magick Image::ExifTool.

file , . , :

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.";
}

.

+2

. , . libmagic, . , , , . :: ExifTool

use Image::ExifTool "ImageInfo";

my $info = ImageInfo(shift || die "Give an image file!\n");

print "This is a ", $info->{FileType}, "\n";

use Data::Dump "pp";
print "Here more...\n";
pp $info;
+1

, . perl- CPAN "Image-Size-3.300 > Image:: Size". image "type". .

#!/usr/bin/perl 

use Image::Size;

print "Content-type: text/html\n\n";

my ($image_width, $image_height, $image_type) = imgsize("path/image.jpg");

unless ($image_type =~ /JPG/i
 || $image_type =~ /PNG/i) {
print "The file is not a valid JPG or PNG.";
}

#To see the results printed to the web browser
 print "<br>(image.jpg) $image_width - $image_height - $image_type<br>\n";

exit(0);
+1

All Articles