PHP生成缩略图


PHP生成缩略图


<?php

if(isset($_GET['filename']) and file_exists($_GET['filename'])){
	$file = $_GET['filename'];
	$thumb_file = str_replace('photos', 'thumbs', $file);
	if(file_exists($thumb_file)){
		header('Content-type: image/jpeg');
		echo file_get_contents($thumb_file);
		exit();
	}else{
		if(!file_exists(dirname($thumb_file))){
			mkdir(dirname($thumb_file), 0755, 1);
		}
	}
	$size = isset($_GET['size']) ? intval($_GET['size']) : 120 ;
	list($width, $height, $type) = getimagesize($file);
	$tmp = imagecreatetruecolor($size, $size);
	if($width > $height){
		$x = ceil(($width - $height) / 2);
		$y = 0;
		$s = $height;
	}else{
		$x = 0;
		$y = ceil(($height - $width) / 2);
		$s = $width;
	}
	switch ($type){
		// 1 = GIF,2 = JPG,3 = PNG,4 = SWF,5 = PSD,6 = BMP
		case '2':
			header('Content-type: image/jpeg');
			$img = imagecreatefromjpeg($file);
			break;
		case '3':
			header('Content-type: image/png');
			$img = imagecreatefrompng($file);
			break;
		case '1':
			header('Content-type: image/gif');
			$img = imagecreatefromgif($file);
			break;
	}
	imagecopyresampled($tmp, $img, 0, 0 , $x, $y, $size, $size, $s, $s);
	switch ($type){
		// 1 = GIF,2 = JPG,3 = PNG,4 = SWF,5 = PSD,6 = BMP
		case '2':
			imagejpeg($tmp, null, 95);
			break;
		case '3':
			imagepng($tmp);
			break;
		case '1':
			imagegif($tmp);
			break;
	}
	imagejpeg($tmp, $thumb_file, 95);
	imagedestroy($img);
	imagedestroy($tmp);
}


发表回复