Image Upload and Cropping with PHP and Jquery

Are you looking for Image Upload and Cropping with PHP and Jquery. This post will describe very easy way to image upload and cropping using  jquery and PHP. You can implement the same code in asp.net also.

Image cropping is the most important and required part in social media projects. 9lession implemented image cropping functionalities such as upload image file into physical location, cropping image using jquery and resizing image into small resolution.

The idea is that the user uploads a picture,  selects which area to crop and saves it under a specific directory.

 

cropimage
We are looking for new features to be added to this plugin, please leave your requests in the comments on the following page : JQuery / PHP Upload and Crop – Feature Request

live-demo-tech-blog

Click here to download source code script

Sample database design for Users.

Users
Contains user details username, password, email, profile_image and profile_image_small etc.

//code start here
CREATE TABLE `users` (
`uid` int(11) AUTO_INCREMENT PRIMARY KEY,
`username` varchar(255) UNIQUE KEY,
`password` varchar(100),
`email` varchar(255) UNIQUE KEY,
`profile_image` varchar(200),
`profile_image_small` varchar(200),
)

index.php
Contains PHP code uploading image into uploads folder physical location and image path updating in users table set profile_image.

< ?php
include('db.php');
session_start();
$session_id=$_SESSION['user'];//  Session ID
$path = "uploads/";
$valid_formats = array("jpg", "png", "gif", "bmp");
if(isset($_POST['submit']))
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['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['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
$image="<h1>Please drag on the image
//HTML Body
< ?php echo $image; ?>
<div id="thumbs" ></div>
<div>
<form id="cropimage" method="post" enctype="multipart/form-data">
Upload your image <input type="file" name="photoimg" id="photoimg" />
<input type="hidden" name="image_name" id="image_name" value="<?php echo($actual_image_name)?/>" />
<input type="submit" name="submit" value="Submit" /> 
</form>
 
</div>

Javascript
$(“img#photo”).imgAreaSelect() – here photo is the ID name of image block and calling imgAreaSelect function for cropping image.

//code start here
 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/
1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="scripts/jquery.imgareaselect.pack.js"></script>
<script type="text/javascript">
function getSizes(im,obj)
{
var x_axis = obj.x1;
var x2_axis = obj.x2;
var y_axis = obj.y1;
var y2_axis = obj.y2;
var thumb_width = obj.width;
var thumb_height = obj.height;
if(thumb_width > 0)
{
if(confirm("Do you want to save image..!"))
{
$.ajax({
type:"GET",
url:"ajax_image.php?t=ajax&img="+$("#image_name").val()+"&w="+
thumb_width+"&h="+thumb_height+"&x1="+x_axis+"&y1="+y_axis,
cache:false,
success:function(rsponse)
{
$("#cropimage").hide();
$("#thumbs").html("");
$("#thumbs").html("");
}
});
}
}
else
alert("Please select portion..!");
}
$(document).ready(function () 
{
$('img#photo').imgAreaSelect({
aspectRatio: '1:1',
onSelectEnd: getSizes
});
});
</script>

ajax_image.php
Contains simple PHP code, resizing cropped image into 100 x 100 pixel and updating into users table profile_image_small.

//code start here
< ?php
include('db.php');
session_start();
$session_id=$_SESSION['user']; // Or Session ID
$t_width = 100; // Maximum thumbnail width
$t_height = 100; // Maximum thumbnail height
$new_name = "small".$session_id.".jpg"; // Thumbnail image name
$path = "uploads/";
if(isset($_GET['t']) and $_GET['t'] == "ajax")
{
extract($_GET);
$ratio = ($t_width/$w); 
$nw = ceil($w * $ratio);
$nh = ceil($h * $ratio);
$nimg = imagecreatetruecolor($nw,$nh);
$im_src = imagecreatefromjpeg($path.$img);
imagecopyresampled($nimg,$im_src,0,0,$x1,$y1,$nw,$nh,$w,$h);
imagejpeg($nimg,$path.$new_name,90);
mysql_query("UPDATE users SET profile_image_small='$new_name' WHERE uid='$session_id'");
echo $new_name."?".time();
exit;
}
?>

db.php
PHP database configuration file

//code start here
< ?php
$mysql_hostname = "Host name";
$mysql_user = "UserName";
$mysql_password = "Password";
$mysql_database = "Database Name";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
mysql_select_db($mysql_database, $bd) or die("Could not select database");
?>

 

Comments

  1. Anonymous says

    When I crop an image that is not jpg it doesn’t save the resized image, any ideas why this could be happening? Thanks!

    • Anonymous says

      About the extensions:
      Instead of just having:
      $im_src = imagecreatefromjpeg($path.$img);

      You need to add have something like this:
      switch($extension){
      case ‘bmp': $im_src = imagecreatefromwbmp($path.$img); break;
      case ‘gif': $im_src = imagecreatefromgif($path.$img); break;
      case ‘jpg': $im_src = imagecreatefromjpeg($path.$img); break;
      case ‘png': $im_src = imagecreatefrompng($path.$img); break;
      default : return “Unsupported picture type!”;
      }

      Of curse, you will need to send the extension parameter thrugh the URL, something like this:
      url:”ajax_image.php?t=ajax&img=”+$(“#image_name”).val()+”&extension=”+extFile+”&w=”+thumb_width+”&h=”+thumb_height+”&x1=”+x_axis+”&y1=”+y_axis,

  2. Anonymous says

    This is awesome script for Image Upload and Cropping with PHP and JQuery, but how do i get it to save only the re-sized/thumbnail not the the original images.

  3. Kumar Mani says

    Hi, I was trying your code for cropping and uploading image in my project, after crop the image saved but I want to crop the same image multiple times. All crops the image parts should save into only one frame.

Leave a Reply

Your email address will not be published. Required fields are marked *