Sunday, October 25, 2009

上傳圖片後自動更名

<?php        
function getFileName($str) {
$i = strripos($str,".");
if (!$i) { return ""; }
$l = strlen($str);
$ext = substr($str,0,$i);
return $i;
}

if ($_SERVER['REQUEST_METHOD'] == "POST")
{
$imagePathDir = "/hospital/admin/thumb/";
// Generate One and only filename to avoid repeated files
$imgNewName = md5(uniqid(rand()));

// Modify filenames
$pext = getFileName($file_name);
$file_name = substr_replace($file_name,$imgNewName,0,$pext);

// Get uploaded files
$src = imagecreatefromjpeg($_FILES['file']['tmp_name']);

// Obtain width and height of source pic
$src_w = imagesx($src);
$src_h = imagesy($src);

// Assume that the width is less than 145 and height is less than 125
if($src_w > $src_h){
$thumb_w = 145;
$thumb_h = intval($src_h / $src_w * 145);
}
else{
$thumb_h = 125;
$thumb_w = intval($src_w / $src_h * 125);
}

// Build up thumbnail
$thumb = imagecreatetruecolor($thumb_w, $thumb_h);

// Begin to 'thumb' pic
imagecopyresampled($thumb, $src, 0, 0, 0, 0, $thumb_w, $thumb_h, $src_w, $src_h);

// Saving 'thumbed' pic into Directory
imagejpeg($thumb, "thumb/".$file_name);

// Copy original pic into directory
copy($_FILES['file']['tmp_name'], "images/".$file_name);


/* Any other task u wish to do is assign below */

}

0 comments:

Post a Comment