Below is a watermark function I made for my php photo upload script. I am curious if there is a better way of doing the parts that check for the file type, notice I had to use that part of code 2 times
<?PHP
function watermark($source_file,$source_width,$source_height,$image_type) {
//first image below will be large then small in 1line if/else
$watermarksize = ($source_width > 300) ? '../images/fpwatermark.gif' : '../images/fpwatermark.gif';
//now add the watermark to the image.
$watermark = imagecreatefromgif($watermarksize);
switch ($image_type) {
case 'gif':
$image = imagecreatefromgif($source_file);
break;
case 'jpg':
$image = imagecreatefromjpeg($source_file);
break;
case 'png':
$image = imagecreatefrompng($source_file);
break;
default:
$image = imagecreatefromjpeg($source_file);
break;
}
//get the dimensions of the watermark
list($water_width, $water_height) = getimagesize($watermarksize);
// Water mark process
$x = $source_width - $water_width - 8; //horizontal position
$y = $source_height - $water_height - 8; //vertical positon
// imagesy($image) can be the source images width
imagecopymerge($image, $watermark, $x, $y, 0, 0, $water_width, $water_height, 65);
switch ($image_type) {
case 'gif':
imagegif($image, $source_file, 90);
break;
case 'jpg':
imagejpeg($image, $source_file, 90);
break;
case 'png':
imagepng($image, $source_file, 90);
break;
default:
imagejpeg($image, $source_file, 90);
break;
}
imagedestroy($image);
return $source_file;
}
?>
You could use dynamic function calls, as illustrated below. This code is subtly different from yours since it returns if an invalid image type is provided rather than assume that it’s jpeg. If you insist on that behavior it should be easy enough to change, tough.
It’s not always the case that all these image types are supported by PHP so you might want to use function_exists() to check for that before calling them. Calling a non-existant function is a fatal error in PHP.
If you have the exif extension installed you could use exif_imagetype() to automatically detect the type of the image.
Another option that’s a bit more elegant, but also contains more code is to use polymorfism:
I realize that you’ll probably prefer the first one. 🙂