2012-03-31 50 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