Techumber
Home Blog Work

Live Image Crop Script With PHP & Jquery

Published on September 16, 2012

Hi guys, Today I’ll show you how to create Live Image Crop and resize script using PHP and Jquery. This tutorial is extended of our previous tutorial Live Image resize Script With PHP. If you are new please go to check that before you start it. Check out the demo…

![](//4.bp.blogspot.com/-GcVXXzti7IE/UFgu8SgZe5I/AAAAAAAAArI/xPQoG-WDsxs/s1600/Live-Image-Crop-With-PHP-Jquery.png)

Demo download

imgAreaSelect(Plugin)

First of all, I would like to thank //odyniec.net/projects/imgareaselect/ for this amazing _imgAreaSelect_ jquery plugin. Actually, I want to develop similar plugin before but luckily I found this one with more than what I need. It’s very easy to install and you can completely customize it is as you need.

We are going to create

index.php process.php process.js

index.php(HTML)

<html lang="en">
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <title>Image Crop using php and javascript:techumber.com</title>
  <link rel="stylesheet" href="lib/imgareaselect/css/imgareaselect-default.css" />
  <link rel="stylesheet" href="css/style.css">
</head>
<body>
  <header class="logo wrap">
 <a href="http:/www.techumber.com">
 <img src="//demos.techumber.com/asserts/img/logostd.png" alt="techumber.com logo"/>
  </a>
 </header>
<div class="container wrap">
<div class="left">
<?php

// if image uploaded this section will show

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 show

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">
<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/1.11.0/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>

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.

index.php(PHP)

<?php
$image = '';
$err = '';

if (isset($_POST['submit']))
{

	// error variable to hold your error message

	$err = "";
	$path = "uploads/";

	// all 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";
		}
	}
}
?>

This code will be used to upload the image to the server folder. I used _uploads_ folder in this example.

process.js

$(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();
  });
});

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.

process.php

<?php

// This will be new name of cropped image

$newImgName = rand(10, 100) . ".jpg";

// uploads path

$path = "uploads/";

if ($_GET)
{

	// to get all $_GET values

	extract($_GET);

	// to get extinction 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;
}

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. Here the code is almost similar to our previous tutorial Live Image Resize Script With PHP code. Hope! u like it.