Function resizeImage
/** * * @param type $width * @param type $height * @param type $mode * @param type $imageName * @param type $extension * @return string */ function resizeImage($width, $height, $mode, $imageName,$extension) { $docRoot = getenv("DOCUMENT_ROOT"); /* Get original image x y */ $tmpNM = $_FILES['files']['tmp_name']; list($w, $h) = getimagesize($_FILES['files']['tmp_name']); /* calculate new image size with ratio */ $ratio = max($width / $w, $height / $h); $h = ceil($height / $ratio); $x = ($w - $width / $ratio) / 2; $w = ceil($width / $ratio); /* new file name */ if ($mode == 'userphoto') { $path = $docRoot . '/upload/userphoto/' . $imageName; } /* read binary data from image file */ $imgString = file_get_contents($_FILES['files']['tmp_name']); /* create image from string */ $image = imagecreatefromstring($imgString); $tmp = imagecreatetruecolor($width, $height); imagecopyresampled($tmp, $image, 0, 0, $x, 0, $width, $height, $w, $h); $fileTypes = array('jpg', 'jpeg', 'jpe', 'png', 'bmp', 'gif'); // File extensions /* Save image */ $extension = strtolower($extension); switch ($extension) { case 'jpg': case 'jpeg': case 'jpe': imagejpeg($tmp, $path, 100); break; case 'png': imagepng($tmp, $path,0); break; case 'gif': imagegif($tmp, $path, 100); break; case 'bmp': imagewbmp($tmp, $path); break; default: exit; break; } return $path; /* cleanup memory */ imagedestroy($image); imagedestroy($tmp); }
How to use Code
HTML Code
PHP Code
//List of thumbnails $sizes = array(200 => 200, 150 => 150); $files=array(); if (!empty($_FILES)) { //Clean the image name $_FILES['files']['name'] = preg_replace('/[^a-zA-Z0-9_.-]/', '', strtolower(trim($_FILES['files']['name']))); //Temporary file, type, name $tmpNM = $_FILES['files']['tmp_name']; $imageType = $_FILES['files']['type']; $imageName = $_FILES['files']['name']; //Get image extension $imageNameType = explode(".", $_FILES['files']['name']); //Type of images support for uploading $fileMimeTypes = array('image/jpeg', 'image/png', 'image/bmp', 'image/gif'); // mime extensions $fileTypes = array('jpg', 'jpeg', 'jpe', 'png', 'bmp', 'gif'); // File extensions if (in_array(strtolower($imageNameType[1]), $fileTypes)) { $fullImageName = time('his') . '_' . $_FILES['files']['name']; foreach ($sizes as $w => $h) { $files[] = $this->resizeImage($w, $h, 'userphoto', "{$w}_{$fullImageName}", $imageNameType[1]); } } }