Perl Imgsize not working in loop?

2019-08-07 04:22发布

问题:

I've tested getting the image size using perl with the following simple code while sitting in one directory:

#!/usr/local/bin/perl
use Image::Size;

my $x;
my $y; 
my $id;

opendir my $dh, "."  or die "$0: opendir: $!";
 ($x, $y, $id) = imgsize("test_image.png");
 print $x." , ".$y."\n";

This worked fine, it gave me the correct width and height of the image. Then I incorporated it into my larger code, where I'm looping through folders and files. So the bigger code is this:

# I first get into a certain folder, which consists of lots of other folders, 
# each named one of the elements in the @views array 
# which I've declared somewhere else

foreach $view(@views)
{   my $folder = $view; 
    opendir my $dh, "$classfolder\\organizedbyviews\\$folder\\cropped"  or die "$0: opendir: $!";
    print "......\nReading folder: $view \n.....\n";

    my $file;
    while ($file = readdir($dh)) {
        #read the image's width and height
        my $w;
        my $h;
        my $id;
        ($w, $h, $id) = imgsize($file);

        print $file.": ".$w.", ".$h."\n";
     }
}

Now when I run this, I know there's no issue with my paths etc because my output correctly lists the image files in the folders, but it just doesn't output their dimensions:

......
Reading folder: view1
......
.: ,
..: ,
file1.jpg: , 
file2.jpg: , 
file3.jpg: , 
file4.jpg: , 
file5.jpg: , 
......
Reading folder: view2
......
.: ,
..: ,
file1.jpg: , 
file2.jpg: , 
file3.jpg: , 
file4.jpg: , 
file5.jpg: , 

and so on.

Why is the imgsize() function suddenly not working?

回答1:

Add the path in front of the filename:

$file = "$classfolder\\organizedbyviews\\$folder\\cropped\\".$file;