2012-03-31 51 views
0

我使用此代码来保存图像使用Image::Grab特定的URL。但图像被保存在0字节中,所以没有图像。Perl:保存图像从网络

#!/usr/bin/perl 

use Image::Grab; 
$pic->url('hhttp://www.vikingskipet.no/cam_1.jpg') 
$pic->grab; 

# Now to save the image to disk 
$time = time(); 
open(IMAGE, ">$time.jpg") || die"$time.jpg: $!"; 
binmode IMAGE; # for MSDOS derivations. 
print IMAGE $pic->image; 
close IMAGE; 

我希望有人能帮助我。我使用cronjobs来每分钟运行脚本。

+1

'使用严格的;使用警告;' - 除非您在发布之前将样本过多地剪下来,否则'$ pic'未被初始化。 (并检查网址。) – Mat 2012-03-31 10:06:22

回答

3

只使用getstore()LWP::Simple

+0

我尝试过使用它。 使用LWP :: Simple; $ time = time(); getstore(“http://www.vikingskipet.no/cam_1.jpg”,“$ time.jpg”); 似乎没有工作。它根本不会将图像保存在服务器上。 – Kaizokupuffball 2012-03-31 10:19:44

2

您在HTTP

+0

没有看到。谢谢! – Kaizokupuffball 2012-03-31 10:06:48

+0

它是否解决了您的问题? – 2012-03-31 11:08:07

6

有一个额外的h将主要的问题是,你还没有创建Image::Grab对象。您应该在所有程序开始时当然是use strictuse warnings,尤其是当您需要帮助时。这将允许Perl找到并报告您可能忽略的简单错误。

这个程序做你的原意,以及把文件名转化为更可读的形式

use strict; 
use warnings; 

use Image::Grab; 

my $pic = Image::Grab->new; 

$pic->url('http://www.vikingskipet.no/cam_1.jpg'); 
$pic->grab; 

my $file = do { 
    my @dt = reverse((localtime)[0..5]); 
    $dt[0] += 1900; 
    $dt[1]++; 
    sprintf "%04d-%02d-%02d.%02d.%02d.%02d.jpg", @dt; 
}; 

open my $img, '>:raw', $file or die qq(Can't open "$file" for output: $!); 
print $img $pic->image; 
close $img or die qq(Failed to close "$file": $!); 

print qq(Image file "$file" saved successfully\n); 
+0

@daxim:感谢您的建议,但我宁愿将代码保留原样(仅使用'time()'作为文件名),而不是引入另一个模块来解决此问题 - 尽管是标准模块。 – Borodin 2012-03-31 14:22:00