You are here:Home » PHP » Resizing Uploaded Files - PHP

Resizing Uploaded Files - PHP


Resizing Uploaded Files - PHP

In this tutorial, I will teach you how to resize uploaded files to make them have either a fixed size, or a certain percent of its former size. The advantage of resizing uploaded files are many:

  1. The File's size would greatly reduce, enabling better performance.
  2. General fitness and a more elegant look especially for a photo gallery.
image resizing script
Download

This tutorial requires the two plugins below:
  1. jQuery-1.5.1.min.js
  2. jQuery.form.js
We will also create  two files below:
  1. index.php
  2. upload.php
You will create two folders- uploads(store normal image) and thumb(contain resized images). I'm sure you will like this. Don't forget to leave behind a comment, or post us an update.

Index.php

<html>
<head>
<title>Ajax file upload with image resizing - Ohwofosirai Desmond</title>
<script type="text/javascript" src="jquery-1.5.1.min.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script>
$(document).ready(function() {
  $('#uploader').live('change', function()            {
  $("#msg").html('');
  $("#msg").text('Uploading....');
  $("#upload").ajaxForm({
            target: '#msg'
                        }).submit();

            });
        });             
</script>
</head>
<body>
<DIV id="uploadfile" style="font-size:12px">
<div>
<p style="margin:2px; font-weight:bold; font-size:16px;">
Ajax file upload with image resizing.</p>
This ajax uploader uses the AjaxForm plugin.
</div>
<form id="upload" method="post" action="upload.php" enctype="multipart/form-data">
<p/><label>Upload profile picture</label>
<br/><input type="file" id="uploader" name="file"/>
</form>
<DIV id="msg"></DIV>
</DIV>

</body>
</html>

Upload.php - php image resizing

<?php
/*initialize values($h=new height, $w=new width, $dir=storage location)*/
    $h=60; $w=60;
    extract($_POST);
    //file format validation
    $arr=array();
    $valid_formats = array("jpg", "png", "gif", "bmp");
    $filename=$_FILES['file']['name'];
    $arr = explode(".",$filename);
    $ext=$arr[count($arr)-1];
    if(!in_array($ext, $valid_formats))
    quit("Invalid file format");

    //validate filesize
    if ($_FILES['file']['size']>2048)
    quit("File too large. Max: 2MB");

    if(is_uploaded_file($_FILES['file']['tmp_name']))
    move_uploaded_file($_FILES['file']['tmp_name'],"upload/".$filename);

    //call function to resize and upload file                                                 
    $resize=resize("upload/".$filename, "thumb/".$filename, 100);
    if ($resize) quit('<img src="thumb/'.$filename.'" alt="image" id="msg"/>');
    else quit('Unknown Error! Please Retry');

    /*------------------------------------------------------------------------------------------
    NOTE: This php function called "resize" had been copied from elsewhere on the internet.
    help me if you have some info that can help me link them.
    ------------------------------------------------------------------------------------------*/
    /* This function resizes an image by calculating percentage of new height using width specified.
    resize(file_location, file_destination, new_width) */
function resize($orig_file,$thumb_file,$prop){
    $img = $orig_file;
    $constrain = true;
    $w = $prop;
    $h = $prop;
     $percent=0;
    // get image size of img
    $x = @getimagesize($img);
    // image width
    $sw = $x[0];
    // image height
    $sh = $x[1];

    if ($percent > 0) {
        // calculate resized height and width if percent is defined
        $percent = $percent * 0.01;
        $w = $sw * $percent;
        $h = $sh * $percent;
    } else {
        if (isset ($w) AND !isset ($h)) {
            // autocompute height if only width is set
            $h = (100 / ($sw / $w)) * .01;
            $h = @round ($sh * $h);
        } elseif (isset ($h) AND !isset ($w)) {
            // autocompute width if only height is set
            $w = (100 / ($sh / $h)) * .01;
            $w = @round ($sw * $w);
        } elseif (isset ($h) AND isset ($w) AND isset ($constrain)) {
            // get the smaller resulting image dimension if both height
            // and width are set and $constrain is also set
            $hx = (100 / ($sw / $w)) * .01;
            $hx = @round ($sh * $hx);
            $wx = (100 / ($sh / $h)) * .01;
            $wx = @round ($sw * $wx);
            if ($hx < $h) {
                $h = (100 / ($sw / $w)) * .01;
                $h = @round ($sh * $h);
            } else {
                $w = (100 / ($sh / $h)) * .01;
                $w = @round ($sw * $w);
            }
        }
    }
    $im = @ImageCreateFromJPEG ($img) or // Read JPEG Image
    $im = @ImageCreateFromPNG ($img) or // or PNG Image
    $im = @ImageCreateFromGIF ($img) or // or GIF Image
    $im = false; // If image is not JPEG, PNG, or GIF
    if (!$im) {
        // We get errors from PHP's ImageCreate functions...
        // So let's echo back the contents of the actual image.
        readfile ($img);
    } else {
        // Create the resized image destination
        $thumb = @ImageCreateTrueColor ($w, $h);
        // Copy from image source, resize it, and paste to image destination
        @ImageCopyResampled ($thumb, $im, 0, 0, 0, 0, $w, $h, $sw, $sh);
        // Output resized image
        @ImageJPEG ($thumb,$thumb_file);
    }
return true;
}//resize function end here

    //echo errors and quit, if any.
    function quit($msg){
    echo $msg;
    exit;
    }                                         
?>


resize file php, file cropping, file php script

0 comments:

Post a Comment