How to upload and resize image in php with example
In this tutorial, We will tell you how to upload and resize image in PHP. upload images are the most important part of the website.
In this example, we will upload the image and create a resize image in PHP. if we will upload a large image on our website then our website runs slow. so we need to resize image width and height. the image resize will help our website improve SEO(search engine optimization).
Sometimes, we need to create thumbnails of images. so, we can easily create a thumbnail using the below example. we can also create thumbnails of images in different formate like png, jpg, jpeg, and gif.
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 | <?php if(isset($_FILES['image'])){ $file_name = $_FILES['image']['name']; // The file name $file_temp = $_FILES['image']['tmp_name']; // File in the PHP tmp folder $getext = explode(".", $file_name); // Split file name into an array using the dot $fileExt = end($getext); // Now target the last array element to get the file extension $wmax = 300; $hmax = 300; $new_file_path ='./image/thumb/'; img_resize($file_temp,$wmax, $hmax, $fileExt,$new_file_path); } function img_resize($target,$w, $h, $ext,$new_file_path) { list($w_orig, $h_orig) = getimagesize($target); $scale_ratio = $w_orig / $h_orig; if (($w / $h) > $scale_ratio) { $w = $h * $scale_ratio; } else { $h = $w / $scale_ratio; } $img = ""; $ext = strtolower($ext); if ($ext == "gif"){ $img = imagecreatefromgif($target); } else if($ext =="png"){ $img = imagecreatefrompng($target); } else { $img = imagecreatefromjpeg($target); } $tci = imagecreatetruecolor($w, $h); imagecopyresampled($tci, $img, 0, 0, 0, 0, $w, $h, $w_orig, $h_orig); if ($ext == "gif"){ $res=imagegif($tci, $new_file_path.time(). "_thump.gif"); } else if($ext =="png"){ $res=imagepng($tci, $new_file_path.time(). "_thump.png"); } else { $res=imagejpeg($tci, $new_file_path.time(). "_thump.jpg"); } } ?> <form action="<?= $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data"> <input type="file" name="image" /> <input type="submit"/> </form> |
Please follow and like us: