Squalle
Squalle

Reputation: 13

Perl Image Gallery Issue

I'm trying to build an image gallery. I'm using Perl to grab a list of images in a directory and display them. The images are all different heights and widths. The script will grab the image names, find the width and height of each, and display them on the page, along with the rest of the HTML for the page. My images are 1.jpg, 2.jpg, 3.jpg... up to 15 (for now, many many more will be added later).

My issue is when I need the script to generate the image name, it stops getting the image's dimensions. If I hard code the image, it works and tells me the dimensions.

Here's what I have (I know this might be rough...)

#!/usr/bin/perl

use Image::Magick;
my $magick = Image::Magick->new;

opendir(DIR, "./images/");
@images = readdir(DIR);
close(DIR);

print "Content-type: text/html\n\n";

foreach $file (@images) {
    $magick->Read( './images/$file' );
    my $width  = $magick->Get('width');
    my $height = $magick->Get('height');
    print "<img src=\"images/$file\" width=\"$width\" height=\"$height\">\n";
}

If I change $magick->Read( './images/$file' ); to $magick->Read( './images/1.jpg' ); it works. Of course, it then shows 1.jpg 15 times, but it is able to display the width and height. Any ideas why this is? I assume I just missed something, but I've been working on this all day.

Thank you.

Upvotes: 0

Views: 124

Answers (2)

Borodin
Borodin

Reputation: 126732

As has been explained, readdir will return both file and directory names, as well as the pseudo-directories . and ... You also have a problem with appending the file name to the directory name.

It is best to use File::Spec to manipulate file paths, so as to avoid any mistakes of this sort, and you should use the -f file test to discard all directory names.

Here's an example

#!/usr/bin/perl
use strict;
use warnings;
use 5.010;
use autodie;

use File::Spec::Functions qw/ catfile /;
use Image::Magick;

my $dir = 'images';

print "Content-type: text/html\n\n";

opendir my ($dh), $dir;

while (my $node = readdir $dh) {

    my $file = catfile($dir, $node);
    next unless -f $file;

    my $magick = Image::Magick->new;
    $magick->Read($file);
    my $width  = $magick->Get('width');
    my $height = $magick->Get('height');

    print qq{<img src="$file" width="$width" height="$height">\n};
}

Upvotes: 1

Quentin
Quentin

Reputation: 943649

Your main issue is that single quoted strings do not interpolate variables. You are looking for an image with the filename $image and not using the value of the variable $image.

Use " instead of '


Additionally, you aren't doing anything to check that the the filenames actually represent images or url encoding the names when you turn them into URLs for the HTML.

Upvotes: 3

Related Questions