我正试图在我的网站上实现一个图像破解器,但我遇到了一些问题,我不知道如何解决。
预期行为:一旦用户通过文件输入从磁盘中选择了他们的图片,它就会显示一个模式,您必须裁剪图片(具有预定义的纵横比),然后他们必须单击"裁剪"按钮来确认他们有什么裁剪,以便将裁剪的图片显示到img标记中。
发生了什么:所选图像在模态上显示一毫秒,然后弹出并在控制台上打印404错误。
我实际上在使用Cropper
这是我的尝试:
var image = document.getElementById('imageToCrop');
document.getElementById("customFile").onchange = function (e) { // customFile is the id of my input file !
if (typeof FileReader !== "undefined") {
let size = e.target.files[0].size;
if (size > 2048000) {
$('#fileTooBigErrorModal').modal({
show: true
})
this.value = "";
document.getElementById("customFileLabel").innerHTML = "Choose file";
} else {
document.getElementById("customFileLabel").innerHTML = e.target.files[0].name;
image.src = ""
var reader = new FileReader();
var cropBoxData;
var canvasData;
var cropper;
reader.onload = function (evt) {
image.src = evt.target.result;
};
reader.readAsDataURL(e.target.files[0]);
$('#cropModal').on('shown.bs.modal', () => {
image.setAttribute('src', e.target.files[0].name);
cropper = new Cropper(image, {
viewMode: 3,
aspectRatio: 4 / 1,
ready: function () {
//Should set crop box data first here
cropper.setCropBoxData(cropBoxData).setCanvasData(canvasData);
},
crop: function (event) {
//test
}
});
$('#cropBtn').click((e) => {
cropper.getCroppedCanvas({ width: 800, height: 200 }).toBlob((blob) => {
$('#result').append('<img src="' + blob + '" alt="Result picture">');
});
$('#cropModal').modal('hide');
})
}).on('hidden.bs.modal', function () {
cropBoxData = cropper.getCropBoxData();
canvasData = cropper.getCanvasData();
cropper.destroy();
});
$('#cropModal').modal('show');
}
}
};
<div class="modal fade" id="cropModal" tabindex="-1" role="dialog" aria-labelledby="cropModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="cropModalLabel">Crop</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div>
<img id="imageToCrop" src="#" alt="Picture to crop">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" id="cropBtn" class="btn btn-primary">Crop</button>
</div>
</div>
</div>
</div>
我找了大约3天的解决方案。还是想不通
加载图像后实例化cropper对象。
以下是我解决问题的方法:
reader.onloadend = e => {
this.imgTarget.attr("src", (e.target as any).result);
this.cropperObj = new Cropper(this.imgTarget[0] as HTMLImageElement, { // option attibutes here
});
}