以下是我最终用于 jquery.cropper 的设置:
jQuery( image ).cropper({
preview: '.img-preview',
viewMode:3,
aspectRatio: 1 / 1,
strict: true,
guides: false,
dragMode: 'move',
movable: true,
highlight: true,
dragCrop: false,
cropBoxResizable: true,
data: { width: 580, height: 580 },
autoCropArea: 0,
minWidth: 580,
minHeight: 580,
maxWidth: 2400,
maxHeight: 2400,
ready: function (event) {
jQuery(this).cropper('setData', {
width: 580,
height: 580
});
},
crop: function(event) {
jQuery('#height').val(Math.round(event.detail.height));
jQuery('#width').val(Math.round(event.detail.width));
jQuery('#x').val(Math.round(event.detail.x));
jQuery('#y').val(Math.round(event.detail.y));
jQuery('#angle').val(Math.round(event.detail.rotate));
jQuery('#scalex').val(Math.round(event.detail.scaleX));
jQuery('#scaley').val(Math.round(event.detail.scaleY));
}
});
在裁剪按钮上,我必须添加它,它将裁剪区域的大小调整为 580x580。我正在使用它向用户展示它的外观预览。
$('#btnCrop').click(function() {
var croppedImageDataURL = image.cropper('getCroppedCanvas', {width:580, height:580}).toDataURL("image/jpg");
result.append( jQuery('<img>').attr('src', croppedImageDataURL) );
});
我有另一个用于 appendFileandSubmit() 操作的函数。我在那里添加了相同的东西,将图像缩小到 580x580。
// click function to handle the image
function appendFileAndSubmit(){
var form = document.getElementById("cropperform");
var croppedImageDataURL = image.cropper('getCroppedCanvas', {width:580, height:580}).toDataURL("image/jpg");
// Split the base64 string in data and contentType
var block = croppedImageDataURL.split(";");
// Get the content type of the image
var contentType = block[0].split(":")[1];// In this case "image/gif"
// get the real base64 content of the file
var realData = block[1].split(",")[1];// In this case "R0lGODlhPQBEAPeoAJosM...."
// Convert it to a blob to upload
var blob = b64toBlob(realData, contentType);
// Create a FormData and append the file with "image" as parameter name
var formDataToUpload = new FormData(form);
formDataToUpload.append("image", blob);
/**
* The following code should send 2 post parameters:
* filename: providen by the text input
* image: a file, dinamically added from a base64 string using javascript
*
* Is up to you how to receive the file in the Server side.
*/
jQuery.ajax({
url:"finish-image.php",
data: formDataToUpload,// Add as Data the Previously create formData
type:"POST",
contentType:false,
processData:false,
cache:false,
dataType:"json", // Change this according to your response from the server.
error:function(err){
console.error(err);
},
success:function(data){
console.log(data);
jQuery('#FinalStep .outputMsg').html('<p>Success!</p>');
},
complete:function(){
console.log("Request finished.");
}
});
}
这会将 580x580 的图像提交给脚本进行处理。