I wrote a function to resize and upload images...it works, but only for one image. So if I call the function three times, I end up with 3 copies of the last image.....
function uploadImage($name,$width,$height,$size,$path='content/user_avatars/')
{
//===================================================
//Handle image upload
$upload_error=0;
//Picture
$img = $_FILES[$name]['name'];
if($img)
{
$file = stripslashes($_FILES[$name]['name']);
$ext = strtolower(getExt($file));
if($ext!='jpg' && $ext!='jpeg' && $ext!='png' && $ext!='gif')
{
$error_msg = "Unknown extension";
$upload_error = 1;
return array($upload_error,$error_msg);
}
if(filesize($_FILES[$name]['tmp_name'])>$size*1024)
{
$error_msg = "Max file size of ".($size*1024)."kb exceeded";
$upload_error = 2;
return array($upload_error,$error_msg);
}
$newFile = time().'.'.$ext;
resizeImg($_FILES[$name]['tmp_name'],$ext,$width,$height);
$store = copy($_FILES[$name]['tmp_name'],$path.$newFile);
if(!$store)
{
$error_msg = "Uploading failed";
$upload_error = 3;
return array($upload_error,$error_msg);
}
else
{
return array($upload_error,$newFile);
}
}
}
//=========================================================================================
//Helper Functions
function getExt($str)
{
$i = strpos($str,".");
if(!$i)
{
return "";
}
$l = strlen($str)-$i;
$ext = substr($str,$i+1,$l);
return $ext;
}
function resizeImg($file,$ext,$width,$height)
{
list($aw,$ah) = getimagesize($file);
$scaleX = $aw/$width;
$scaleY = $ah/$height;
if($scaleX>$scaleY)
{
$nw = round($aw*(1/$scaleX));
$nh = round($ah*(1/$scaleX));
}
else
{
$nw = round($aw*(1/$scaleY));
$nh = round($ah*(1/$scaleY));
}
$new_image = imagecreatetruecolor($nw,$nh);
imagefill($new_image,0,0,imagecolorallocatealpha($new_image,255,255,255,127));
if($ext=='jpg'||$ext=='jpeg')
{
$src_image = imagecreatefromjpeg($file);
}
else if($ext=='gif')
{
$src_image = imagecreatefromgif($file);
}
else if($ext=='png')
{
$src_image = imagecreatefrompng($file);
}
imagecopyresampled($new_image,$src_image,0,0,0,0,$nw,$nh,$aw,$ah);
if($ext=='jpg'||$ext=='jpeg')
{
imagejpeg($new_image,$file,100);
}
else if($ext=='gif')
{
imagegif($new_image,$file);
}
else if($ext=='png')
{
imagepng($new_image,$file,9);
}
imagedestroy($src_image);
imagedestroy($new_image);
}
I have a form with two upload fields, 'face_pic' and 'body_pic', and I want to upload these two to the server and resize them before storing. Any ideas?