• 27th July 2010 - By admin

    Many times when you upload a image somewhere you want to resize it to different dimensions based off of a maximum width or height. Here is a simple script that does this for you, using a HTML form and a PHP script. We start with the PHP script that will run if our $_GET['do'] is set to “upload.” Then we include the HTML form that has three inputs (max width, max height, image file).

    Here is the PHP:

    <?php

    // index.php

    function generate_resized_image(){

    $max_dimension = 800; // Max new width or height, can not exceed this value.
    $dir = "./images/"; // Directory to save resized image. (Include a trailing slash – /)

    // Collect the post variables.
    $postvars = array(
    "image"    => trim($_FILES["image"]["name"]),
    "image_tmp"    => $_FILES["image"]["tmp_name"],
    "image_size"    => (int)$_FILES["image"]["size"],
    "image_max_width"    => (int)$_POST["image_max_width"],
    "image_max_height"   => (int)$_POST["image’_max_height"]
    );

    // Array of valid extensions.
    $valid_exts = array("jpg","jpeg","gif","png");

    // Select the extension from the file.
    $ext = end(explode(".",strtolower(trim($_FILES["image"]["name"]))));

    // Check not larger than 175kb.
    if($postvars["image_size"] <= 179200){

    // Check is valid extension.
    if(in_array($ext,$valid_exts)){

    if($ext == "jpg" || $ext == "jpeg"){
    $image = imagecreatefromjpeg($postvars["image_tmp"]);
    }
    else if($ext == "gif"){
    $image = imagecreatefromgif($postvars["image_tmp"]);
    }
    else if($ext == "png"){
    $image = imagecreatefrompng($postvars["image_tmp"]);
    }
    // Grab the width and height of the image.
    list($width,$height) = getimagesize($postvars["image_tmp"]);

    // If the max width input is greater than max height we base the new image off of that, otherwise we
    // use the max height input.
    // We get the other dimension by multiplying the quotient of the new width or height divided by
    // the old width or height.

    if($postvars["image_max_width"] > $postvars["image_max_height"]){

    if($postvars["image_max_width"] > $max_dimension){
    $newwidth = $max_dimension;
    } else {
    $newwidth = $postvars["image_max_width"];
    }
    $newheight = ($newwidth / $width) * $height;

    } else {

    if($postvars["image_max_height"] > $max_dimension){
    $newheight = $max_dimension;
    } else {
    $newheight = $postvars["image_max_height"];
    }
    $newwidth = ($newheight / $height) * $width;
    }

    // Create temporary image file.
    $tmp = imagecreatetruecolor($newwidth,$newheight);

    // Copy the image to one with the new width and height.
    imagecopyresampled($tmp,$image,0,0,0,0,$newwidth,$newheight,$width,$height);

    // Create random 4 digit number for filename.
    $rand = rand(1000,9999);
    $filename = $dir.$rand.$postvars["image"];
    // Create image file with 100% quality.
    imagejpeg($tmp,$filename,100);
    return "<strong>Image Preview:</strong><br/>
    <img src=\""
    .$filename."\" border=\"0\" title=\"Resized  Image Preview\" style=\"padding: 4px 0px 4px 0px;background-color:#e0e0e0\" /><br/>
    Resized image successfully generated. <a href=\""
    .$filename."\" target=\"_blank\" name=\"Download your resized image now!\">Click here to download your image.</a>";

    imagedestroy($image);
    imagedestroy($tmp);
    } else {
    return "File size too large. Max allowed file size is 175kb.";
    }
    } else {
    return "Invalid file type. You must upload an image file. (jpg, jpeg, gif, png).";
    }
    }

    if(isset($_GET["do"])){
    if($_GET["do"] == "upload"){
    $upload_and_resize = generate_resized_image();
    } else {
    $upload_and_resize = "";
    }
    } else {
    $upload_and_resize = "";
    }

    ?>

    Here is the HTML:

    <form action="./index.php?do=upload" method="post" enctype="multipart/form-data">
    <table width="100%" align="center" border="0" cellpadding="2" cellspacing="0">
    <tr>
    <td align="left" width="100">
    Max Width:</td>
    <td align="left"><input name="image_max_width" style="width: 120px" type="text" maxlength="4" /> px.</td>
    </tr>
    <tr>
    <td align="left">
    Max Height:</td>
    <td align="left"><input type="text" name="image_max_height" style="width: 120px" type="text" maxlength="4" /> px.</td>
    </tr>
    <tr>
    <td align="left">
    Image:</td>

    <td align="left"><input type="file" name="image" size="40" /></td></tr>
    <tr>
    <td align="left" colspan="2">
    <ol style="margin:0;padding:3px 0px 3px 15px">
    <li>Max file size: 175 KB.</li>
    <li>Allowed extensions: jpg, jpeg, gif, png.</li>
    <li>Max Dimension: <em>800</em>px.</li>
    </ol>
    </tr>
    <tr>
    <td align="left" colspan="2">
    <input type="submit" name="submit" value="Submit!" style="font: 14pt verdana" />
    </td>
    </tr>
    </table>
    </form>

    This will create a form that looks like this:

    Max Width: px.
    Max Height: px.
    Image:
    1. Max file size: 175 KB
    2. Allowed extensions: jpg, jpeg, gif, png.
    3. Max Dimension: 800px.

    Then we just have to call the functions returned value ($upload_and_resize).

    <div id="upload">
    <?php echo $upload_and_resize; ?>
    </div>

  • 17 Responses to “PHP Upload and Resize Image”

    • I truly loved this brilliant article. Please continue this awesome work. Regards, Duyq.

    • Dear admin, thnx for sharing this blog post. I found it wonderful. Best regards, Victoria…

    • Sherman Sanger on July 27, 2010

      Hey! I just wanted to thank you for your really interesting story. Postings like this are a seriously brilliant way to help me learn English, but I think I got the story ok :) Thank you again!

    • Arlene Whetsel on July 28, 2010

      I found your entry interesting so I’ve added a Trackback to it on my weblog :) … thanks

    • This site is a walk-through for all the information you wanted about this and didn’t know who to ask. Look here, and you’ll definitely find it.

    • evony requirements on July 28, 2010

      Dear admin, thnx for sharing this blog post. I found it wonderful. Best regards, Victoria…

    • Usually I do not post on blogs, but I would like to say that this article really forced me to do so! Thanks, really nice article.

    • residential lawn service on July 28, 2010

      It’s the first time I have heard that in Macedonia, obits are an unusual observe. You have wonderfully written the post. I have liked your way of writing this. Thanks for sharing this.

    • e cooking games on July 28, 2010

      Aw, this was a really quality post. In theory I’d like to write like this too – taking time and real effort to make a good article… but what can I say… I procrastinate alot and never seem to get something done.

    • Dorthea Alamos on July 28, 2010

      I just needed to say that I found your blog via Goolge and I am glad I did. Keep up the good work and I will make sure to bookmark you for when I have more free time away from the books. Thanks again!

    • hot polish women on July 28, 2010

      Hey admin, very informative blog post! Pleasee continue this awesome work..

    • [...] the rest here: PHP Upload and Resize Image | bgallz.org | Web coding & design … Share and [...]

    • Edmund Serafine on August 4, 2010

      I really liked reading your blog. Very good posts! Please keep posting such excellent cotent.

    • Babyschale on August 6, 2010

      Wonderful to read!

    • James Lake on August 7, 2010

      You have an awesome blog! Keep up the good work. I found you on Yahoo.

    • Eustolia Rokicki on August 13, 2010

      thanks, very well written post, found it through a random google search and i shared it on my facebook

    • uggs on August 18, 2010

      Hi there, just wanted to leave a quick comment about the interface of your blog. It is really easy on the eye while also being catchy. I think I will do something similar for my blog as well. Thanks for the nice blog share.

    Leave a Reply

    Powered by WP Hashcash


bgallz.org is for training purposes only. Its content is to be used at the risk of the user. We do not guaruntee its accuracy.