This is a followup on the previous article where I described how to hide images from direct access. After we upload some movies and pictures in the movie/picture albums on dutchie.org, we also would like to have a nice way to browse through those albums.
Photo’s
There are a large number of photo album sites out there and many of them have their own way of viewing the pictures. What most have in common is that there’s a collection of thumbnails for all the pictures.
Using PHP and GD, it’s quite easy to create a thumbnail for a picture. We don’t want to do this dynamically every time somebody wants to look at the thumbnails as that would get rather expensive on CPU time, therefore we will create a thumbnail every time a picture is uploaded, store this thumbnail on the filesystem, and set the thumbnail attribute of our Foto class to the location of the thumbnail.
As we discussed in the previous article, we don’t want to simply store these thumbnails in the documentroot of the webserver as it’s hard to check the proper authorisation that way. Therefore we’ll store the thumbnails for the pictures in the same folder as the originals of the picture and use a similar script to display the thumbnails as we use for displaying the originals.
Basically the algorithm to use becomes:
- Store uploaded picture in FOTODIR
- Depending on what image type was uploaded, use PHP GD’s imagecreatefrompng(), imagecreatefromgif() or imagecreatefromjpeg() to create a GD image object
- Get the width and height of the uploaded picture using PHP GD’s imagesx() and imagesy() functions
- Create a temporary 100×75 GD image object
- Resize the earlier original image object into the newly created temporary object using imagecopyresampled()
- Store the temporary GD image object into FOTODIR . “thumb_” ….
In PHP code it doesn’t look much more complicated:
if (move_uploaded_file($tmpfile,$target_path)) {
$this->filename = basename($filename);
$this->pictype = strtoupper($extension);
switch ($this->GetAttr("pictype")) {
case "PNG":
$img = imagecreatefrompng(FOTODIR . $this->filename);
break;
case "GIF":
$img = imagecreatefromgif(FOTODIR . $this->filename);
break;
case "JPEG":
case "JPG":
$img = imagecreatefromjpeg(FOTODIR . $this->filename);
break;
default:
$this->SetError("onbekend foto type");
return FALSE;
}
$width = imagesx($img);
$height = imagesy($img);
$dbg->Dbg(DBG::DBG, "width: $width height: $height");
$thumb = imagecreatetruecolor(100,75);
imagecopyresampled($thumb, $img, 0, 0, 0, 0, 100, 75, $width, $height);
imagepng($thumb, FOTODIR . $thumbnail);
$this->thumbnail = $thumbnail;
}
}
Video’s
With video’s the algorithm to create a thumbnail is bit more complex. The Debian distribution’s PHP version that I’m using does not come with builtin video manipulation support. There is however a very nice extension that uses the ffmpeg tools. On Debian this extension is easily installed using:
$ sudo apt-get install php5-ffmpeg