{"id":11,"date":"2014-07-19T03:39:50","date_gmt":"2014-07-19T03:39:50","guid":{"rendered":"http:\/\/www.scriptut.com\/?p=11"},"modified":"2024-05-25T05:53:56","modified_gmt":"2024-05-25T05:53:56","slug":"upload-and-resize-image-in-php","status":"publish","type":"post","link":"https:\/\/scriptut.com\/php\/upload-and-resize-image-in-php\/","title":{"rendered":"How to Upload and Resize Images in PHP"},"content":{"rendered":"\n<p>When building web applications in PHP, handling image uploads and resizing them is a common task. In this tutorial, we will demonstrate how to create a simple PHP script to upload and resize images. This guide covers creating a file upload form and processing the uploaded file to resize it.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Creating the File Upload Form<\/h3>\n\n\n\n<p>First, we need to create a form that allows users to upload their images. We will create two files: <code><strong>index.php<\/strong><\/code> for the form and <code><strong>upload_file.php<\/strong><\/code> to handle the upload and resizing process.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">index.php<\/h2>\n\n\n\n<p>This file contains the HTML form for users to upload their images.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;!DOCTYPE html>\n&lt;html>\n&lt;head>\n    &lt;title>Upload and Resize Image&lt;\/title>\n&lt;\/head>\n&lt;body>\n    &lt;form action=\"upload_file.php\" method=\"post\" enctype=\"multipart\/form-data\">\n        &lt;label for=\"file\">Filename:&lt;\/label>\n        &lt;input type=\"file\" name=\"file\" id=\"file\">&lt;br>\n        &lt;input type=\"submit\" name=\"submit\" value=\"Submit\">\n    &lt;\/form>\n&lt;\/body>\n&lt;\/html>\n<\/code><\/pre>\n\n\n\n<p>The<strong> <code>enctype=\"multipart\/form-data\"<\/code><\/strong> attribute is crucial for file uploads via POST. Without this, the file upload will not work.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Handling the File Upload and Resizing<\/h2>\n\n\n\n<p>When the form is submitted, the file data is sent to <code>upload_file.php<\/code> for processing. This file will handle the upload and resizing logic.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">upload_file.php<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;?php\nif ($_FILES) {\n    $allowedExts = array(\"gif\", \"jpeg\", \"jpg\", \"png\");\n    $temp = explode(\".\", $_FILES&#91;\"file\"]&#91;\"name\"]);\n    $extension = end($temp);\n\n    if ((($_FILES&#91;\"file\"]&#91;\"type\"] == \"image\/gif\")\n    || ($_FILES&#91;\"file\"]&#91;\"type\"] == \"image\/jpeg\")\n    || ($_FILES&#91;\"file\"]&#91;\"type\"] == \"image\/jpg\")\n    || ($_FILES&#91;\"file\"]&#91;\"type\"] == \"image\/pjpeg\")\n    || ($_FILES&#91;\"file\"]&#91;\"type\"] == \"image\/x-png\")\n    || ($_FILES&#91;\"file\"]&#91;\"type\"] == \"image\/png\"))\n    &amp;&amp; ($_FILES&#91;\"file\"]&#91;\"size\"] &lt; 2000000)\n    &amp;&amp; in_array($extension, $allowedExts)) {\n\n        if ($_FILES&#91;\"file\"]&#91;\"error\"] > 0) {\n            echo \"Return Code: \" . $_FILES&#91;\"file\"]&#91;\"error\"] . \"&lt;br>\";\n        } else {\n            $filename = \"upload\/\" . $_FILES&#91;\"file\"]&#91;\"name\"];\n            move_uploaded_file($_FILES&#91;\"file\"]&#91;\"tmp_name\"], $filename);\n            \n            $resized_filename = \"upload\/\" . 'thumb-'.$_FILES&#91;\"file\"]&#91;\"name\"];\n            resize_image($filename, $resized_filename, 150, 150);\n\n            echo \"Stored in: \" . $filename;\n        }\n    } else {\n        echo \"Invalid file\";\n    }\n}\n\nfunction resize_image($file, $destination, $w, $h) {\n    list($source_width, $source_height, $source_type) = getimagesize($file);\n    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));\n\n    switch ($ext) {\n        case 'jpg':\n        case 'jpeg':\n            $source_gdim = imagecreatefromjpeg($file);\n            break;\n        case 'png':\n            $source_gdim = imagecreatefrompng($file);\n            break;\n        case 'gif':\n            $source_gdim = imagecreatefromgif($file);\n            break;\n        default:\n            return;\n    }\n\n    $source_aspect_ratio = $source_width \/ $source_height;\n    $desired_aspect_ratio = $w \/ $h;\n\n    if ($source_aspect_ratio > $desired_aspect_ratio) {\n        $temp_height = $h;\n        $temp_width = (int)($h * $source_aspect_ratio);\n    } else {\n        $temp_width = $w;\n        $temp_height = (int)($w \/ $source_aspect_ratio);\n    }\n\n    $temp_gdim = imagecreatetruecolor($temp_width, $temp_height);\n    imagecopyresampled($temp_gdim, $source_gdim, 0, 0, 0, 0, $temp_width, $temp_height, $source_width, $source_height);\n\n    $x0 = ($temp_width - $w) \/ 2;\n    $y0 = ($temp_height - $h) \/ 2;\n    $desired_gdim = imagecreatetruecolor($w, $h);\n    imagecopy($desired_gdim, $temp_gdim, 0, 0, $x0, $y0, $w, $h);\n\n    switch ($ext) {\n        case 'jpg':\n        case 'jpeg':\n            imagejpeg($desired_gdim, $destination, 100);\n            break;\n        case 'png':\n            imagepng($desired_gdim, $destination);\n            break;\n        case 'gif':\n            imagegif($desired_gdim, $destination);\n            break;\n    }\n\n    imagedestroy($desired_gdim);\n}\n?>\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>File Validation<\/strong>: The script checks the file type and size to ensure it is an acceptable image.<\/li>\n\n\n\n<li><strong>File Upload<\/strong>: The <code>move_uploaded_file<\/code> function uploads the image to the <code>upload<\/code> directory.<\/li>\n\n\n\n<li><strong>Image Resizing<\/strong>: The <code>resize_image<\/code> function resizes the uploaded image to the specified dimensions and saves it with a new name.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Detailed Resizing Function<\/h3>\n\n\n\n<p>The <code>resize_image<\/code> function is responsible for resizing the uploaded image. It supports JPEG, PNG, and GIF formats. Here&#8217;s a breakdown of the function:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Get Image Dimensions and Type<\/strong>: The <code>getimagesize<\/code> function retrieves the width, height, and type of the image.<\/li>\n\n\n\n<li><strong>Create Image Resource<\/strong>: Based on the file extension, it creates an image resource using <code>imagecreatefromjpeg<\/code>, <code>imagecreatefrompng<\/code>, or <code>imagecreatefromgif<\/code>.<\/li>\n\n\n\n<li><strong>Calculate New Dimensions<\/strong>: The function calculates the new dimensions while maintaining the aspect ratio.<\/li>\n\n\n\n<li><strong>Resample Image<\/strong>: The <code>imagecopyresampled<\/code> function creates a new true color image with the specified dimensions.<\/li>\n\n\n\n<li><strong>Crop Image<\/strong>: If necessary, the image is cropped to the desired size.<\/li>\n\n\n\n<li><strong>Save Resized Image<\/strong>: Finally, the resized image is saved using <code>imagejpeg<\/code>, <code>imagepng<\/code>, or <code>imagegif<\/code>.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>Uploading and resizing images in PHP is a straightforward process. By following the steps outlined in this tutorial, you can easily implement this functionality in your own projects. This guide provides the core code needed to upload and resize images, ensuring your application can handle images effectively.<\/p>\n\n\n\n<p>For a complete working example, you can download the source code <a href=\"#\">here<\/a>.<\/p>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Handle image uploads and resizing easily with our step-by-step PHP code example.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3],"tags":[],"class_list":["post-11","post","type-post","status-publish","format-standard","hentry","category-php"],"_links":{"self":[{"href":"https:\/\/scriptut.com\/wp-json\/wp\/v2\/posts\/11","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/scriptut.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/scriptut.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/scriptut.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/scriptut.com\/wp-json\/wp\/v2\/comments?post=11"}],"version-history":[{"count":3,"href":"https:\/\/scriptut.com\/wp-json\/wp\/v2\/posts\/11\/revisions"}],"predecessor-version":[{"id":350,"href":"https:\/\/scriptut.com\/wp-json\/wp\/v2\/posts\/11\/revisions\/350"}],"wp:attachment":[{"href":"https:\/\/scriptut.com\/wp-json\/wp\/v2\/media?parent=11"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/scriptut.com\/wp-json\/wp\/v2\/categories?post=11"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/scriptut.com\/wp-json\/wp\/v2\/tags?post=11"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}