Digital World Freelancer

The Digital World Freelancer group is applying latest Technologies Like HTML, CSS, CSS3, JavaScript, JQuery, PHP and more...... for website designing & developing... reach at our organization http://www.digitalworldfreelancer.com

Facebook Page

Monday, October 13, 2014

Upload, Crop and Resize images with PHP!



One of the most common actions on the modern web application is upload, crop and resize of images, whether for avatar use or general use of resized images in galleries or as thumbnails.

Upload image with PHP:

We will start this tutorial with a classic image upload so you can easily understand the means and methods of how uploading files in PHP works.

In this first example we will a form for uploading files and save that file in a folder on the server, but only if that file is an image.

To upload a file, you need a form with a special input field type of file. So, open your favorite editor and paste in this code and save it as form.php:

<!DOCTYPE html>
<html>
<head>
    <title>Upload Files using normal form and PHP</title>
</head>
<body>
  <form enctype="multipart/form-data" method="post" action="upload.php">
    <div class="row">
      <label for="fileToUpload">Select a File to Upload</label><br />
      <input type="file" name="fileToUpload" id="fileToUpload" />
    </div>
    <div class="row">
      <input type="submit" value="Upload" />
    </div>
  </form>
</body>
</html>

One thing that you already noticed is probably the enctype attribute of our form. It basically prepares the form for binary data, like the contents of a file.

Next step is to create a file that will handle our uploaded images. Go ahead, create upload.php file and paste this in:

<?php
// fileToUpload is the name of our file input field
if ($_FILES['fileToUpload']['error'] > 0) {
    echo "Error: " . $_FILES['fileToUpload']['error'] . "<br />";
} else {
    echo "File name: " . $_FILES['fileToUpload']['name'] . "<br />";
    echo "File type: " . $_FILES['fileToUpload']['type'] . "<br />";
    echo "File size: " . ($_FILES['fileToUpload']['size'] / 1024) . " Kb<br />";
    echo "Temp path: " . $_FILES['fileToUpload']['tmp_name'];
}


Now, open form.php in browser and try to select and upload a file. If everything went fine, you should see some info about the uploaded file when you submit a form.

Nice start, but user can now upload anything to your server and basically blow it to pieces. So, let’s modify the upload.php code to check if uploaded file is actually an image:

<?php
if ($_FILES['fileToUpload']['error'] > 0) {
    echo "Error: " . $_FILES['fileToUpload']['error'] . "<br />";
} else {
    // array of valid extensions
    $validExtensions = array('.jpg', '.jpeg', '.gif', '.png');
    // get extension of the uploaded file
    $fileExtension = strrchr($_FILES['fileToUpload']['name'], ".");
    // check if file Extension is on the list of allowed ones
    if (in_array($fileExtension, $validExtensions)) {
        echo 'Uploaded file is allowed!';
    } else {
        echo 'You must upload an image...';
    }
}

So, we checked if the file is an image and now we can write code to move that image in some folder on the server, so change your code to this:

<?php
if ($_FILES['fileToUpload']['error'] > 0) {
    echo "Error: " . $_FILES['fileToUpload']['error'] . "<br />";
} else {
    // array of valid extensions
    $validExtensions = array('.jpg', '.jpeg', '.gif', '.png');
    // get extension of the uploaded file
    $fileExtension = strrchr($_FILES['fileToUpload']['name'], ".");
    // check if file Extension is on the list of allowed ones
    if (in_array($fileExtension, $validExtensions)) {
        // we are renaming the file so we can upload files with the same name
        // we simply put current timestamp in fron of the file name
        $newName = time() . '_' . $_FILES['fileToUpload']['name'];
        $destination = 'uploads/' . $newName;
        if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $destination)) {
            echo 'File ' .$newName. ' succesfully copied';
        }
    } else {
        echo 'You must upload an image...';
    }
}


Before you try this out, create a folder named uploads in the directory in which the code is in.

Congratulations, you successfully uploaded and saved a file on the server.

Crop and resize images with PHP:



Now the fun part begins. We will resize the uploaded image and save resized version in uploads folder so you can easily use them later. We can do this from scratch, but there are plenty of useful libraries on the web that does an excellent job.

I will use a great ImageManipulator class by Phil Brown. Download it and put inside your working directory.

Now, update your upload.php file:


<?php
// include ImageManipulator class
require_once('ImageManipulator.php');

if ($_FILES['fileToUpload']['error'] > 0) {
    echo "Error: " . $_FILES['fileToUpload']['error'] . "<br />";
} else {
    // array of valid extensions
    $validExtensions = array('.jpg', '.jpeg', '.gif', '.png');
    // get extension of the uploaded file
    $fileExtension = strrchr($_FILES['fileToUpload']['name'], ".");
    // check if file Extension is on the list of allowed ones
    if (in_array($fileExtension, $validExtensions)) {
        $newNamePrefix = time() . '_';
        $manipulator = new ImageManipulator($_FILES['fileToUpload']['tmp_name']);
        // resizing to 200x200
        $newImage = $manipulator->resample(200, 200);
        // saving file to uploads folder
        $manipulator->save('uploads/' . $newNamePrefix . $_FILES['fileToUpload']['name']);
        echo 'Done ...';
    } else {
        echo 'You must upload an image...';
    }
}


The same class can be used to crop the image, so let’s change the code so the image cropped to 200×130 px. We want to crop the center of the image, so the good parts are intact, so we have to calculate crop coordinates:


<?php
// include ImageManipulator class
require_once('ImageManipulator.php');

if ($_FILES['fileToUpload']['error'] > 0) {
    echo "Error: " . $_FILES['fileToUpload']['error'] . "<br />";
} else {
    // array of valid extensions
    $validExtensions = array('.jpg', '.jpeg', '.gif', '.png');
    // get extension of the uploaded file
    $fileExtension = strrchr($_FILES['fileToUpload']['name'], ".");
    // check if file Extension is on the list of allowed ones
    if (in_array($fileExtension, $validExtensions)) {
        $newNamePrefix = time() . '_';
        $manipulator = new ImageManipulator($_FILES['fileToUpload']['tmp_name']);
        $width  = $manipulator->getWidth();
        $height = $manipulator->getHeight();
        $centreX = round($width / 2);
        $centreY = round($height / 2);
        // our dimensions will be 200x130
        $x1 = $centreX - 100; // 200 / 2
        $y1 = $centreY - 65; // 130 / 2

        $x2 = $centreX + 100; // 200 / 2
        $y2 = $centreY + 65; // 130 / 2

        // center cropping to 200x130
        $newImage = $manipulator->crop($x1, $y1, $x2, $y2);
        // saving file to uploads folder
        $manipulator->save('uploads/' . $newNamePrefix . $_FILES['fileToUpload']['name']);
        echo 'Done ...';
    } else {
        echo 'You must upload an image...';
    }
}



Now you learned how to upload, resize and crop images using pure PHP.

No comments: