我想使用WWW下载图像:Mechanize并将文件名保存到文件名中(宽x高,字节),但无法弄清楚如何将字节提取为可读格式 - my img_bytes = format_bytes( ????,precision => 2); 感谢。
use strict;
use warnings;
use File::Basename;
use Data::Dumper;
use Number::Format qw(format_bytes);
use WWW::Mechanize;
my $url = '';
my $mech = WWW::Mechanize->new();
$mech->get( $url );
my @img = $mech->find_all_images(url_regex => qr/\.(?:jpg|png)$/);
foreach my $img (@img) {
my $filename = basename($img->url);
$filename =~ /^(.*?)(\.\w+)$/;
my ($name,$ext) = ($1,$2);
my $img_width = $img->width;
my $img_height = $img->height;
my $img_size = ' ('.$img_width.' x '.$img_height.', '.$img_bytes.')';
$mech->get( $img->url, ':content_file' => $name.$img_size.$ext );
}
答案 0 :(得分:6)
将文件解压缩到临时文件,然后运行my $bytes = -s $tempfilename;
,然后重命名该文件。并且您确实意识到->width
和->height
来自标记,而不是图像的实际宽度和高度,对吧?
以下是我可能会编写代码的方法:
#!/user/bin/env perl
use strict;
use warnings;
use autodie;
use WWW::Mechanize;
use File::Basename;
use File::Temp qw/tempfile/;
use Image::Info qw/image_info dim/;
use Number::Format qw/format_bytes/;
my $url = 'http://www.perl.org';
my $mech = WWW::Mechanize->new;
$mech->get( $url );
for my $img ($mech->find_all_images(url_regex => qr/\.(?:jpg|png)$/)) {
my ($name, undef, $ext) = fileparse($img->url, "jpg", "png");
(undef, my $temp) = tempfile;
$mech->get( $img->url, ':content_file' => $temp );
my ($w, $h) = dim image_info $temp;
my $s = format_bytes -s $temp, precision => 2;
my $dim = "($w x $h, $s)";
rename $temp, "$name$dim.$ext";
}