Lets define some PHP functions well be calling on for our PHP image tutorial series. We define all these functions in a file named functions.phtml and call it in our PHP code through a PHP include_once()
, this way we dont bother with the functions in our PHP image code.
This first function allows us to determine if the requested image file is an image is_image()
.
1 2 3 4 5 6 |
/*Define is_image() ****************************************************************************************************/ function is_image$var1 $t=strtouppersubstr$var1,-3,3; $t2=strtouppersubstr$var1,-4,4; if$t=="GIF" ||$t=="PNG" ||$t=="JPG" ||$t2=="JPEG" return true; return false; |
This function returns the extension for any file getExtension().
1 2 3 4 5 6 |
/*Define getExtension() ****************************************************************************************************/ function getExtension$file $pos = strrpos$file, '.'; if!$pos $photosubmitted = 'Error: Unknown Filetype'; $str = substr$file, $pos, strlen$file; return $str; |
The next function allows us to call the proper MIME type, based on image type, in the header of the PHP code get_mime()
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
/*Define get_mime() ****************************************************************************************************/ function get_mime$var1 $t=strtouppersubstr$var1,-4,4; switch$t case ".JPG": case ".JPEG": return "image/jpeg"; break; case ".GIF": return "image/gif"; break; case ".PNG": return "image/png"; break; default: return ""; break; |
This fourth function allows for the use of the proper PHP image createfromxxx()
call based on image type imagecreatefrom()
.
1 2 3 4 5 6 7 8 9 10 11 12 |
/*Define imagecreatefrom() ****************************************************************************************************/ function imagecreatefrom$file ifstrtouppersubstr$file,-3,3=="JPG" || strtouppersubstr$file,-4,4=="JPEG" $image=imagecreatefromjpeg$file; ifstrtouppersubstr$file,-3,3=="PNG" $image=imagecreatefrompng$file; ifstrtouppersubstr$file,-3,3=="GIF" $image=imagecreatefromgif$file; return $image; |
Lastly this functions will output the image to the browser image_same_type().
1 2 3 4 5 6 7 8 9 10 |
/*Define image_same_type() ****************************************************************************************************/ function image_same_type$file,$image,$quality = 100 ifstrtouppersubstr$file,-3,3=="JPG" || strtouppersubstr$file,-4,4=="JPEG" imagejpeg$image,null,$quality; ifstrtouppersubstr$file,-3,3=="PNG" imagepng$image; ifstrtouppersubstr$file,-3,3=="GIF" imagegif$image; |