Last updated on January 8th, 2020 at 10:21 pm

Image upload and cropping is very important part in every project. In this post i will explain you how to upload image from ajaxform plugin and crop uploaded image with

 

jcrop plugin.
HTML image upload form

This is a simple html form where we can first select and upload image using ajaxform plugin and save to server.

<form action="upload.php" method="post" enctype="multipart/form-data" id="gallery">
		<label>Image: </label>
		<input type="file" name="file" value="">
		<input type="submit" value="Upload" id="UploadButton">
	</form>
	<div id="preview"></div>

Download jquery ajaxform plugin and add to your page/file, after adding plugin you need to add below code to your file to upload image.

<script type="text/javascript" >
		$(document).ready(function() { 
				$('#UploadButton').click(function(){
					$("#preview").html('');
					$("#gallery").ajaxForm({
						target: '#preview'
					}).submit();
				});
		});
	</script>

in above code when user press or click on submit button we can upload selected image to server and save image src to database and in #preview we can display result generated by php page where image is send to upload.

PHP code for image upload and save image link to database

<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db('image_up', $conn);

$path = "upload/";
$valid_formats = array("jpg", "png", "gif", "bmp");
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['file']['name'];
$size = $_FILES['file']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats) && $size<(250*1024))
{
$actual_image_name = time().substr($txt, 5).".".$ext;
$tmp = $_FILES['file']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
mysql_query("insert into image set src='$actual_image_name'");
echo "<h1>Image uploaded </h1><a href='crop.php?id=".mysql_insert_id()."'>Click to crop image</a>";
}
else
echo "failed";
}
else
echo "Invalid file formats..!"; 
}
else
echo "Please select image..!";
}
?>

In above code i add simple image validation code and upload it to selected directory and if image is uploaded and  inserted i return a link where we can crop this image.

Database to save image:

--
-- Table structure for table `image`
--

CREATE TABLE IF NOT EXISTS `image` (
  `id` int(100) NOT NULL AUTO_INCREMENT,
  `src` text NOT NULL,
  `crop_srrc` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

In this i create three columns where we can save id, new image upload location and crop image location.

CROP upload image Jcrop and PHP

JCrop is one of the best cropping plugin to crop image using jquery.  Here is code to use jcrop in your website.

<?php
// Load image from database with selected id.
$id = $_GET['id']; 
$qur = mysql_query("select * from image where id='$id'"); 
while($r = mysql_fetch_array($qur)){ extract($r); $img = $src; } 
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Live Cropping Demo</title>
  <meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
  <script src="jquery.min.js"></script>
  <script src="jquery.Jcrop.min.js"></script>
  <link rel="stylesheet" href="jquery.Jcrop.min.css" type="text/css" />

<script type="text/javascript">

  $(function(){

    $('#cropbox').Jcrop({
      aspectRatio: 1,
      onSelect: updateCoords
    });

  });

  function updateCoords(c)
  {
    $('#x').val(c.x);
    $('#y').val(c.y);
    $('#w').val(c.w);
    $('#h').val(c.h);
  };

  function checkCoords()
  {
    if (parseInt($('#w').val())) return true;
    alert('Please select a crop region then press submit.');
    return false;
  };

</script>
<style type="text/css">
  #target {
    background-color: #ccc;
    width: 500px;
    height: 330px;
    font-size: 24px;
    display: block;
  }


</style>

</head>
<body>

<div class="container">
		<!-- This is the image we're attaching Jcrop to -->
		<img src="upload/<?php echo $img;?>" id="cropbox" />
		<!-- This is the form that our event handler fills -->
		<form action="crop.php" method="post" onsubmit="return checkCoords();">
			<input type="hidden" id="x" name="x" />
			<input type="hidden" id="y" name="y" />
			<input type="hidden" id="w" name="w" />
			<input type="hidden" id="h" name="h" />
			<input type="hidden" name="src" value="<?php echo $img;?>" />
			<input type="submit" value="Crop Image" class="btn btn-large btn-inverse" />
		</form>
	</div>
</body>
</html>

In above code we can create a hidden form in which we can save crop location of image which user select to crop over image and after click on crop button we can crop image from specific part which is selected by user using php as shown bellow.

<?php

// Get request id and load image
$conn = mysql_connect("localhost", "root", "");
mysql_select_db('image_up', $conn);

if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
	$targ_w = $targ_h = 150;
	$jpeg_quality = 90;

	$src = 'upload/'.$_POST['src'];
	$img_r = imagecreatefromjpeg($src);
	$dst_r = ImageCreateTrueColor( $targ_w, $targ_h );

	imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],$targ_w,$targ_h,$_POST['w'],$_POST['h']);

	header('Content-type: image/jpeg');
	imagejpeg($dst_r,null,$jpeg_quality);

	exit; 
	
}
?>

Done hope you like this and this will help in you projects.

Thanks.

Happy coding.

Posted in: php