我正在尝试使用JQuery cropper plugin实现裁剪图片上传系统但是我对裁剪的图像部分感到困惑
问题是
裁剪图像的尺寸大于实际裁剪尺寸
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);
}
})
})
答案 0 :(得分:0)
您可以执行以下操作(这是我自己的代码,只需了解概念即可):
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');
},
});
});
看到我在“ getCroppedCanvas”函数内部传递了几个参数,这将解决存储到服务器的图像大于裁剪大小的问题。
此外,您还可以在options变量内为“裁剪框”设置最小高度和宽度:
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);
}
};