Uploading and resizing an image file with PHP can be accomplished by using the following provided source code. This PHP code example will work with JPEG, GIF, and PNG image files. The following code example shows when submitting from an HTML field input field with the name attribute: promo_image.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
$uploadedFile = $_FILES['promo_image']['tmp_name']; $sourceProperties = getimagesize($uploadedFile); $newFileName = time(); $dirPath = "uploads/Image/"; $ext = pathinfo($_FILES['promo_image']['name'], PATHINFO_EXTENSION); $imageType = $sourceProperties[2]; switch ($imageType) { case IMAGETYPE_PNG: $imageSrc = imagecreatefrompng($uploadedFile); $tmp = imageResize($imageSrc,$sourceProperties[0],$sourceProperties[1]); imagepng($tmp,$dirPath. $newFileName. "_promo.". $ext); break; case IMAGETYPE_JPEG: $imageSrc = imagecreatefromjpeg($uploadedFile); $tmp = imageResize($imageSrc,$sourceProperties[0],$sourceProperties[1]); imagejpeg($tmp,$dirPath. $newFileName. "_promo.". $ext); break; case IMAGETYPE_GIF: $imageSrc = imagecreatefromgif($uploadedFile); $tmp = imageResize($imageSrc,$sourceProperties[0],$sourceProperties[1]); imagegif($tmp,$dirPath. $newFileName. "_promo.". $ext); break; default: echo "Invalid Image type."; exit; break; } move_uploaded_file($uploadedFile, $dirPath. $newFileName. ".". $ext); echo "Image Resize Successfully."; } function imageResize($imageSrc,$imageWidth,$imageHeight) { $newImageWidth =256; $newImageHeight =256; $newImageLayer=imagecreatetruecolor($newImageWidth,$newImageHeight); imagecopyresampled($newImageLayer,$imageSrc,0,0,0,0,$newImageWidth,$newImageHeight,$imageWidth,$imageHeight); return $newImageLayer; } |