PHP generate new an resizing image

< ?PHP     
class HanroadClass
{
	/************************
	generate new an Resizing image by the PHP GD library
	Support picture format: jpg, gif, png
	$source_img:     Source image path
	$target_dir:     Target image path
	$target_name:    Target image name
	$new_width:      Target image width
	$new_height:     Target image height
	$if_cut:         cutting image ?
	1(yes):          Specified high or width generated Images
	0(no):           Proportion generated Images
	**********************/
	function  HrResize($source_img,$target_dir,$target_name,$new_width,$new_height,$if_cut)
	{
		//Get image format
		$img_type   =   strtolower(substr(strrchr($source_img,"."),1));
 
		//Target image path
		$tar_url   =   $target_dir."/".$target_name.".".$img_type;
 
		if($img_type=="jpg")   $temp_img   =   imagecreatefromjpeg($source_img);
		if($img_type=="gif")   $temp_img   =   imagecreatefromgif($source_img);
		if($img_type=="png")   $temp_img   =   imagecreatefrompng($source_img);
 
		//Source image's width and height
		$old_width     =   imagesx($temp_img);
		$old_height   =   imagesy($temp_img);
 
		//Change the ratio of the image before and after
		$new_ratio   =   $new_width/$new_height;
		$old_ratio   =   $old_width/$old_height;
 
		//Generate new image
		if($if_cut=="1")
		{
			$new_width     =   $new_width;
			$new_height   =   $new_height;
			if($old_ratio>=$new_ratio)
			{
				$old_width     =   $old_height*$new_ratio;
				$old_height   =   $old_height;
			}
			else
			{
				$old_width     =   $old_width;
				$old_height   =   $old_width/$new_ratio;
			}
		}
 
		else
		{
			$old_width     =   $old_width;
			$old_height   =   $old_height;
			if($old_ratio>=$new_ratio)
			{
				$new_width     =   $new_width;
				$new_height   =   $new_width/$old_ratio;
			}
			else
			{
				$new_width     =   $new_height*$old_ratio;
				$new_height   =   $new_height;
			}
		}
		$new_img   =   imagecreatetruecolor($new_width,$new_height);
		imagecopyresampled($new_img,$temp_img,0,0,0,0,$new_width,$new_height,$old_width,$old_height);
 
		if($img_type=="jpg")   imagejpeg($new_img,$tar_url,90);
		if($img_type=="gif")   imagegif($new_img,$tar_url);
		if($img_type=="png")   imagepng($new_img,$tar_url);
 
		return $target_name.".".$img_type;
	}
}
?>
 
< ?php
$nesimg=new HanroadClass();
$img1=$nesimg->HrResize("c:\test.jpg","c:\test_1.jpg",120,120,1);
$img2=$nesimg->HrResize("c:\test.jpg","c:\test_2.jpg",120,120,0);
?>
$img1:
<img src="<?php echo $img1;?/>"/><br /><br />
$img2:
<img src="<?php echo $img2;?/>"/>

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

No comments yet.

Leave a comment

(required)

(required)