Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Image shrinking in PHP 1

Status
Not open for further replies.

carlg

Programmer
Jun 23, 2004
88
0
0
US
I'm creating a PHP application where my users will upload pictures.

I have everything in place as far as picture management is concerned (uploading, deleting, etc.).

Only thing I can't figure out is what if a user uploads a picture that is like 5 gig or something like that?

Is there a way to shrink the pictures that the user uploads? Kind of like ebay does when you upload pictures to sell stuff.
 
sure.

if you shrink the size of the photo then its file-size will also shrink.

take a look at imagecopyresampled() and imagecreatetruecolor() in the manual

here is a code snip aswell. pass it the full path, the mimetype and the newsize (max) and it will create and save the shrunk image for you (over the top of the previous image).

if you want to change the location of the saved image, you want to alter the line that's in red. change $pathInfo['directory'] to a different directory in which the web server process has write access.

Code:
function reSizePhoto($file, $type, $newsize = 800){
	switch ($type) {
		
		case 'image/jpeg':
			$src_img = imagecreatefromjpeg($file);
			$func = 'imagejpeg';
			$ext = '.jpeg';
			break;
		case 'image/gif':
			$src_img = imagecreatefromgif($file);
			$func = 'imagegif';
			$ext = '.gif';
			break;
		case 'image/png':
			$src_img = imagecreatefrompng($file);
			$func = 'imagepng';
			$ext = '.png';
			break;
		default:
			die("error - file is not of a supported image type");
	}
	
	if ($src_img == '') {
		die("error - file is not a $type file");
	}
	
	//get current image sizes
	
	$old_x=imagesx($src_img);
	$old_y=imagesy($src_img);
	
	if ($old_x > $old_y){
		$thumb_w=$newsize;
		$thumb_h=$old_y*($newsize/$old_x);
	} elseif ($old_x < $old_y) {
		$thumb_w=$old_x*($newsize/$old_y);
		$thumb_h=$newsize;
	} else {
		$thumb_w= $thumb_h = $newsize; 
	}
	
	$dst_img=imagecreatetruecolor($thumb_w,$thumb_h);
	imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); 
	$pathInfo = pathinfo($file);
	
	[red]$func($dst_img,$pathInfo['directory'].PATH_SEPARATOR.$pathInfo['basename']); [/red]
	imagedestroy($dst_img);
	imagedestroy($src_img);	
	return $file;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top