如何检测文件是否是perl中的图像

时间:2012-06-18 12:31:08

标签: image perl detection

为了设置一些变量,如果我服务器上的给定文件是图像,我需要信息。我对文件的位置和名称一无所知。

有没有办法检测文件是否是图片而不查看文件扩展名?

5 个答案:

答案 0 :(得分:11)

一种简单的方法是通过PerlMagick CPAN模块将工作委托给ImageMagick。 IdentifyPing方法专为此目的而设计。

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的list of supported formats(也包括非图像格式)中列入白名单的子集中的一部分。

答案 1 :(得分:8)

JRFerguson在附加到该问题的评论中提到了file命令。它附带一个C库对应部分libmagic。 Perl绑定称为File::LibMagic

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

表达式对图像类型返回true。

答案 2 :(得分:2)

@JRFerguson首先提到的命令fileFile::LibMagicImage::MagickImage::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.";
}

这个想法只是针对已知的图像格式进行正则表达式。

答案 3 :(得分:1)

你已经有了两个好的答案。在这些情况下,还有一个工具可能很有价值。它将比libmagic解决方案慢,但它有时更适合于附加信息和实用程序。我不知道哪种工具更全面或可能在边缘情况下失败。 Image::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's more...\n";
pp $info;

答案 4 :(得分:1)

这是我做的一种方式。使用perl模块形式CPAN" Image-Size-3.300>图像::尺寸&#34 ;.它还有文件属性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);
相关问题