Techniques » PHP Image Manipulation Functions

Lets define some PHP functions we’ll 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 don’t 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().

[Select Code]

/*Define is_image() ****************************************************************************************************/
function is_image($var1) {
	$t=strtoupper(substr($var1,-3,3));
	$t2=strtoupper(substr($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().

[Select Code]

/*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().

[Select Code]

/*Define get_mime() ****************************************************************************************************/
function get_mime($var1) {
	$t=strtoupper(substr($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().

[Select Code]

/*Define imagecreatefrom() ****************************************************************************************************/
function imagecreatefrom($file)  {
if(strtoupper(substr($file,-3,3))=="JPG" || strtoupper(substr($file,-4,4))=="JPEG"){
	$image=imagecreatefromjpeg($file);
}
if(strtoupper(substr($file,-3,3))=="PNG"){
	$image=imagecreatefrompng($file);
}
if(strtoupper(substr($file,-3,3))=="GIF"){
	$image=imagecreatefromgif($file);
}
return $image;
}

Lastly this functions will output the image to the browser image_same_type().

[Select Code]

/*Define image_same_type() ****************************************************************************************************/
function image_same_type($file,$image,$quality = 100) {
  if(strtoupper(substr($file,-3,3))=="JPG" || strtoupper(substr($file,-4,4))=="JPEG"){
  	imagejpeg($image,null,$quality);
  }
  if(strtoupper(substr($file,-3,3))=="PNG"){
  	imagepng($image);
  }
  if(strtoupper(substr($file,-3,3))=="GIF"){
  	imagegif($image);
  }
}

Post your thoughts below…


Similar Posts:

Leave a Reply