Image Upload Crop and Resize PHP Jquery Script


With below PHP script you can easily Crop and resize Image using PHP and Jquery. You can download entire script from Github.

There are three main files here.

index.php
process.php
process.js

index.php

In this, we have File upload input to upload the image that we want to crop. If the image got uploaded successfully then it will be displayed on the same page. This code will be used to upload the image to the server folder. I used _uploads_ folder in this example.

<?php
$image='';
$err='';
$imgname = null;
if(isset($_POST['submit'])){
 //error variable to hold your error message 
 $err="";
 $path = "uploads/";
 //alled image format will be used for filter 
 $allowed_formats = array("jpg", "png", "gif", "bmp");
 $imgname = $_FILES['img']['name'];
 $tmpname = $_FILES['img']['tmp_name'];
 $size = $_FILES['img']['size'];
 //validate image
 if(!$imgname){
  $err="<strong>Oh snap!</strong>Please select image..!";
  return false;
 }
 if($size > (1024*1024)){
  $err="<strong>Oh snap!</strong>File Size is too large..!";
 }
 list($name, $ext) = explode(".", $imgname);
 if(!in_array($ext,$allowed_formats)){
   $err="<strong>Oh snap!</strong>Invalid file formats only use jpg,png,gif";
   return false;     
 }
 if($ext=="jpg" || $ext=="jpeg" ){
  $src = imagecreatefromjpeg($tmpname);
 }
 else if($ext=="png"){
  $src = imagecreatefrompng($tmpname);
 }
 else {
  $src = imagecreatefromgif($tmpname);
 }
 list($width,$height)=getimagesize($tmpname);
 if($width > 400){
  $newwidth=399;
  $newheight=($height/$width)*$newwidth;
  $tmp=imagecreatetruecolor($newwidth,$newheight);
  imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
  $image = $path.$imgname;
  imagejpeg($tmp,$path.$imgname,100);
  move_uploaded_file($image,$path.$imgname);
 }
 else{
  if(move_uploaded_file($tmpname,$path.$imgname)){
   $image="uploads/".$imgname;
  }
  else{
   $err="<strong>Oh snap!</strong>failed";
  }
 } 
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
 <title>Image Crop using php and javascript</title>
 <link rel="stylesheet" href="lib/imgareaselect/css/imgareaselect-default.css" />
 <link rel="stylesheet" href="css/style.css">
</head>
<body>
  <div class="container wrap">
   <div class="left">
    <?php 
    //if image uploaded this section will shown
     if($image){
      echo "<h2>Select an area on image</h2><img style='' src='".$image."' id=\"imgc\" style='width:100%' >";
     }
    ?>
   </div>
   <div class="right">
     <?php 
     //if image uploaded this section will shown
     if($image){ 
      //echo '<div>' ;
      echo '<h2>Preview</h2>' ;
      echo '<div class="frame">' ;
      echo '<div id="preview">';
      echo '<img src="'.$image.'" >'; 
      echo '</div></div></div>';
      echo "<div id='output'></div>";
      echo "<img src='' id='cropedimg' />";
      echo '<button id="cropbtn">Crop</button>';
     }
    ?>
   </div> 
    <?php
    //if any error while uploading
    if($err){
     echo '<div class="alert alert-error">'.$err.'</div>';
    }
    ?> 
    
    <form id="imgcrop" method="post" enctype="multipart/form-data" style="<?php echo $imgname != null  ? 'display:none;' : ''?>">
    <input type="file" name="img" id="img" />
    <input type="hidden" name="imgName" id="imgName" value="<?php echo($imgname) ?>" />
    <button name="submit">Submit</button>
    </form>
    
    
   <div style="clear:both"></div>
 <script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
 <script type="text/javascript" src="lib/imgareaselect/jquery.imgareaselect.js"></script>
  <script type="text/javascript" src="js/process.js"></script>
</body>
</html>

process.js

This is a client process.js script. In this, we are calling the imgAreaSelect plugin. setValues to store the values in variables. Preview function is used to show preview while we crop the image. Finally, we will call getCimage Ajax call to the process.php to crop the image and return the new cropped image.

$(function () {
  var x1 = 0,
    y1 = 0,
    tw = 0,
    th = 0,
    rw = 300, //preview width;
    rh = 200; //preview height
  //setvalues

  //Calling imgAreaSelect plugin
  $('img#imgc').imgAreaSelect({
    handles: false,
    onSelectEnd: setValue,
    onSelectChange: preview,
    aspectRatio: '4:3',
    fadeSpeed: 200,
    minWidth: 100,
    minHeight: 100,
  });

  //setvalue function
  function setValue(img, selection) {
    if (!selection.width || !selection.height)
      return;
    x1 = selection.x1;
    y1 = selection.y1;
    tw = selection.width;
    th = selection.height;
  }
  //ajax request get the 
  function getCImage() {
    $("#cropbtn").addClass("disabled").html("croping...");
    $.ajax({
      type: "GET",
      url: "process.php?img=" + $("#imgName").val() + "&w=" + tw + "&h=" + th + "&x1=" + x1 + "&y1=" + y1 + "&rw=" + rw + "&rh=" + rh,
      cache: false,
      success: function (response) {
  $("#output").html("");
        $("#cropbtn").removeClass("disabled").html("crop");
        $("#output").html("<h2>Out put</h2><img src='" + response + "' />");
      },
      error: function () {
        alert("error on ajax");
      },
    });
  }
  //preview function
  function preview(img, selection) {
    if (!selection.width || !selection.height) {
      return;
    }
    var scaleX = rw / selection.width;
    var scaleY = rh / selection.height;
    $('#preview img').css({
      width: Math.round(scaleX * img.width),
      height: Math.round(scaleY * img.height),
      marginLeft: -Math.round(scaleX * selection.x1),
      marginTop: -Math.round(scaleY * selection.y1)
    });
  }

  //will triger on crop button click 
  $("#cropbtn").click(function () {
    getCImage();
  });


});

process.php

This is our main script in which we have the code to create the new image depending on the value we get through ajax call.

<?php
// This will be name of croped image
$newImgName = rand(10,100).".jpg"; 
//uploads path
$path = "uploads/";
if($_GET){
 //to get all $_GET values
 extract($_GET);
 //to get extenction of the image
 function getExt($img) {
    $pos = strrpos($img,".");
    if (!$pos) { 
  return "null"; 
    }
    $len = strlen($img) - $pos;
    $ext = substr($img,$pos+1,$len);
    return strtolower($ext);
  }
 
 $wratio = ($rw/$w); 
 $hratio = ($rh/$h); 
 $newW = ceil($w * $wratio);
 $newH = ceil($h * $hratio);
 $newimg = imagecreatetruecolor($newW,$newH);
 $ext=getExt($img);
 if($ext=="jpg" || $ext=="jpeg" ){
  $source = imagecreatefromjpeg($path.$img);
 }
 else if($ext=="png"){
  $source = imagecreatefrompng($path.$img);
 }
 else {
  $source = imagecreatefromgif($path.$img);
 }
 imagecopyresampled($newimg,$source,0,0,$x1,$y1,$newW,$newH,$w,$h);
 imagejpeg($newimg,$path.$newImgName,90);
 echo "uploads/".$newImgName;
 exit;
}
 

Hope you like this tutorial and my be helpful to someone. Please share your comments below.

Post a Comment

0 Comments