I am trying to implement cropped image upload system using JQuery cropper plugin But i am struggled with cropped image section
The issue is
size of the cropped image is larger than the actual cropped size
Html
//load the image for crop
<div class="img-container">
<img id="image" src="latest.jpg">
</div>
//load the cropped image after cropping
<img id="db-image" />
<input type="button" name="" id="getimage" value="getimage"/>
Javascript
//init the cropper plugin
$('#image').cropper({
aspectRatio: 16 / 9,
crop: function(e) {
},
built: function() {
}
});
//load the cropped image into img when click on the button
$('#getimage').click(function(){
//get the cropped image as blob
$('#image').cropper('getCroppedCanvas').toBlob(function(blob){
console.log(blob);
//convert blob to base64 string
var reader = new window.FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function() {
base64data = reader.result;
//display cropped image
$('#db-image').attr('src',base64data);
}
})
})
you can do something like this ( this is my own code , just understand the concept ) :
var $image = $('#jquery_cropper_image');
var cropper = $image.data('cropper');
// Upload cropped image to server if the browser supports `HTMLCanvasElement.toBlob`
cropper.getCroppedCanvas({
width: 160,
height: 90,
minWidth: 500,
minHeight: 500,
maxWidth: 4096,
maxHeight: 4096,
fillColor: '#fff',
imageSmoothingEnabled: false,
imageSmoothingQuality: 'high',
}).toBlob((blob) => {
var formData = new FormData();
//var image_name = document.getElementById('jquery_cropper_image').src;
var image_name = $('#jquery_cropper_image').attr('src');
var image_name = 'cropped_'+image_name.replace('images/','');
formData.append('croppedImage', blob, image_name);
// Use `jQuery.ajax` method
$.ajax('upload_image.php', {
method: "POST",
data: formData,
processData: false,
contentType: false,
success: function(response){
if(response == 'cropped_upload_success'){
console.log('cropped_upload_success');
document.getElementById('success_crop_save_notice').innerText = 'Success!';
}
},
error() {
console.log('Upload error');
},
});
});
see that i have passed few arguments inside the 'getCroppedCanvas' function , that will solve the issue of larger than cropped size image being store to the server.
Additionally you may also set minimum height and width for your 'crop box' inside the options variable:
var options = {
aspectRatio: 1 / 1,
viewMode: 2,
minCropBoxWidth: 500,
minCropBoxHeight: 500,
preview: '.img-preview',
crop: function (e) {
$dataX.val(Math.round(e.detail.x));
$dataY.val(Math.round(e.detail.y));
$dataHeight.val(Math.round(e.detail.height));
$dataWidth.val(Math.round(e.detail.width));
$dataRotate.val(e.detail.rotate);
$dataScaleX.val(e.detail.scaleX);
$dataScaleY.val(e.detail.scaleY);
}
};