Cropping image before upload, always a great idea for server space optimization. Crop feature helps to resize the image as per the required size before uploading on the server. You can reduce the web page size and load time by showing the image with exact display size. The image need to cropped to display the exact dimensions (width and height) in the web page. If your web application has image upload functionality, image crop and resize is very useful.
You can easily upload image and create thumbnail using PHP. But if you want live image upload and crop, jQuery needs to be used with PHP. The jQuery can help to select an area (coordinates) of the image and PHP can help to crop, resize, and upload the image on the server. There are many jQuery plugins available for cropping image, imgAreaSelect is one of them. The imgAreaSelect plugin helps to select an area of an image and implement image cropping and resizing functionality. In this tutorial, we will show you how to upload, crop, and resize image using jQuery and PHP.
Before you get started to implement live image upload and crop functionality, take look the files structure.
image_upload_crop_jquery_php/ ├── index.html ├── upload.php ├── js/ │ ├── jquery.imgareaselect.js │ └── jquery.min.js ├── css/ │ └── imgareaselect.css └── uploads/ └── images/ └── thumb/
jQuery library:
At first, include the jQuery library file.
<!-- jQuery library -->
<script src="js/jquery.min.js"></script>
imgAreaSelect Plugin:
The imgAreaSelect plugin will be used to implement image crop functionality. Include the imgAreaSelect plugin library file.
<!-- imgAreaSelect jQuery plugin -->
<link rel="stylesheet" href="css/imgareaselect.css" />
<script src="js/jquery.imgareaselect.js"></script>
The following JavaScript code generates an instant image preview and allows the user to select an area of the image.
imgAreaSelect()
method.// Check coordinates
function checkCoords(){
if(parseInt($('#w').val())) return true;
alert('Please select a crop region then press upload.');
return false;
}
// Set image coordinates
function updateCoords(im,obj){
var img = document.getElementById("imagePreview");
var orgHeight = img.naturalHeight;
var orgWidth = img.naturalWidth;
var porcX = orgWidth/im.width;
var porcY = orgHeight/im.height;
$('input#x').val(Math.round(obj.x1 * porcX));
$('input#y').val(Math.round(obj.y1 * porcY));
$('input#w').val(Math.round(obj.width * porcX));
$('input#h').val(Math.round(obj.height * porcY));
}
$(document).ready(function(){
// Prepare instant image preview
var p = $("#imagePreview");
$("#fileInput").change(function(){
//fadeOut or hide preview
p.fadeOut();
//prepare HTML5 FileReader
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("fileInput").files[0]);
oFReader.onload = function(oFREvent){
p.attr('src', oFREvent.target.result).fadeIn();
};
});
// Implement imgAreaSelect plugin
$('#imagePreview').imgAreaSelect({
onSelectEnd: updateCoords
});
});
The following HTML creates an image upload form to select an image.
<form method="post" action="upload.php" enctype="multipart/form-data" onsubmit="return checkCoords();">
<p>Image: <input name="image" id="fileInput" size="30" type="file" /></p>
<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 name="upload" type="submit" value="UPLOAD" />
</form>
<p><img id="imagePreview" style="display:none;"/></p>
The upload.php
file handles the image upload, crop, and resize functionality using PHP.
<?php
$error = '';
// If the upload form is submitted
if(isset($_POST["upload"])){
// Get the file information
$fileName = basename($_FILES["image"]["name"]);
$fileTmp = $_FILES["image"]["tmp_name"];
$fileType = $_FILES["image"]["type"];
$fileSize = $_FILES["image"]["size"];
$fileExt = substr($fileName, strrpos($fileName, ".") + 1);
// Specify the images upload path
$largeImageLoc = 'uploads/images/'.$fileName;
$thumbImageLoc = 'uploads/images/thumb/'.$fileName;
// Check and validate file extension
if((!empty($_FILES["image"])) && ($_FILES["image"]["error"] == 0)){
if($fileExt != "jpg" && $fileExt != "jpeg" && $fileExt != "png" && $fileExt != "gif"){
$error = "Sorry, only JPG, JPEG, PNG, and GIF files are allowed.";
}
}else{
$error = "Select an image file to upload.";
}
// If everything is ok, try to upload file
if(empty($error) && !empty($fileName)){
if(move_uploaded_file($fileTmp, $largeImageLoc)){
// File permission
chmod($largeImageLoc, 0777);
// Get dimensions of the original image
list($width_org, $height_org) = getimagesize($largeImageLoc);
// Get image coordinates
$x = (int) $_POST['x'];
$y = (int) $_POST['y'];
$width = (int) $_POST['w'];
$height = (int) $_POST['h'];
// Define the size of the cropped image
$width_new = $width;
$height_new = $height;
// Create new true color image
$newImage = imagecreatetruecolor($width_new, $height_new);
// Create new image from file
switch($fileType) {
case "image/gif":
$source = imagecreatefromgif($largeImageLoc);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
$source = imagecreatefromjpeg($largeImageLoc);
break;
case "image/png":
case "image/x-png":
$source = imagecreatefrompng($largeImageLoc);
break;
}
// Copy and resize part of the image
imagecopyresampled($newImage, $source, 0, 0, $x, $y, $width_new, $height_new, $width, $height);
// Output image to file
switch($fileType) {
case "image/gif":
imagegif($newImage, $thumbImageLoc);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
imagejpeg($newImage, $thumbImageLoc, 90);
break;
case "image/png":
case "image/x-png":
imagepng($newImage, $thumbImageLoc);
break;
}
// Destroy image
imagedestroy($newImage);
// Display cropped image
echo 'CROPPED IMAGE:<br/><img src="'.$thumbImageLoc.'"/>';
}else{
$error = "Sorry, there was an error uploading your file.";
}
}
}
// Display error
echo $error;
?>
Upload Image without Page Refresh using jQuery and PHP
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
Hi. I have just downloaded your script and started playing around with it. This is something that I have been wanting to learn more about for awhile.
One question that I have is: Is there a way to make the crop area already set for a fixed size and all the user can do is move it around. They wouldn’t be able to resize the crop area.
Thanks in advance.
Greg