gpt4 book ai didi

javascript - JQuery 裁剪器插件 : size of the cropped image is larger than the actual cropped size

转载 作者:搜寻专家 更新时间:2023-10-31 21:51:12 30 4
gpt4 key购买 nike

我正在尝试使用 JQuery cropper plugin 实现裁剪图像上传系统但是我在裁剪图像部分时遇到了困难

问题是

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);

}
})
})

js fiddle

最佳答案

你可以这样做(这是我自己的代码,理解概念即可):

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”函数中传递了几个参数,这将解决将大于裁剪尺寸的图像存储到服务器的问题。

此外,您还可以在选项变量中为“裁剪框”设置最小高度和宽度:

 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);
}
};

关于javascript - JQuery 裁剪器插件 : size of the cropped image is larger than the actual cropped size,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41690636/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com