Upload and Crop Image using PHP and jQuery
To crop and upload an image with jQuery and PHP, you can follow these general steps:
- Use a jQuery plugin like “Jcrop” to allow the user to select a crop area on the image.
- When the user has selected the crop area, retrieve the coordinates of the crop area using JavaScript.
- Send the coordinates to a PHP script on the server using an AJAX request.
- In the PHP script, use the GD library to crop the image using the provided coordinates.
- Save the cropped image to a desired location on the server.
- Respond with a success message to the AJAX request to indicate that the image was successfully cropped and uploaded.
<link rel="stylesheet" href="https://unpkg.com/jcrop/dist/jcrop.css">
<script src="https://unpkg.com/jcrop"></script>
Here’s some example code that shows how to achieve this:
<form id="imageUploadForm" method="POST" enctype="multipart/form-data">
<input type="file" name="imageFile" id="imageFile">
<img src="" id="previewImage">
<input type="hidden" name="cropX" id="cropX">
<input type="hidden" name="cropY" id="cropY">
<input type="hidden" name="cropWidth" id="cropWidth">
<input type="hidden" name="cropHeight" id="cropHeight">
<button type="submit" id="uploadButton">Upload</button>
</form>
JavaScript:
$('#imageFile').change(function() {
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(e) {
$('#previewImage').attr('src', e.target.result);
$('#previewImage').Jcrop({
onSelect: function(crop) {
$('#cropX').val(crop.x);
$('#cropY').val(crop.y);
$('#cropWidth').val(crop.w);
$('#cropHeight').val(crop.h);
}
});
}
reader.readAsDataURL(file);
});
$('#imageUploadForm').submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: 'upload.php',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(response) {
alert('Image uploaded successfully!');
},
error: function() {
alert('Error uploading image!');
}
});
});
PHP (upload.php):
if (isset($_FILES['imageFile']) && isset($_POST['cropX']) && isset($_POST['cropY']) && isset($_POST['cropWidth']) && isset($_POST['cropHeight'])) {
$source = $_FILES['imageFile']['tmp_name'];
$destination = 'uploads/' . $_FILES['imageFile']['name'];
$cropX = $_POST['cropX'];
$cropY = $_POST['cropY'];
$cropWidth = $_POST['cropWidth'];
$cropHeight = $_POST['cropHeight'];
$image = imagecreatefromjpeg($source);
$croppedImage = imagecrop($image, ['x' => $cropX, 'y' => $cropY, 'width' => $cropWidth, 'height' => $cropHeight]);
imagejpeg($croppedImage, $destination);
imagedestroy($image);
imagedestroy($croppedImage);
echo 'success';
}