可以在上传之前使用Javascript旋转和裁剪图片库吗?

时间:2019-04-25 13:59:07

标签: javascript php jquery bootstrap-4 croppie

我一直在尝试使用文件阅读器和裁剪文件,以允许用户在上传之前在本地编辑其图像(缩放/旋转/裁剪),但似乎无法使其正常工作。我怀疑这是模式问题,这是一个DOM问题,但是我一辈子都无法弄清楚如何使其工作!


FileReader () stuff
//
//
//create elements for image, edit and delete buttons, then appending to parent div
//
//

//place the new image and button into the new div
newdiv.appendChild(newimage);
newdiv.appendChild(newedit);
newdiv.appendChild(newdelete);

//place the new div into the results div
output.appendChild(newdiv);

//add event listeners to dynamically created buttons
newdelete.addEventListener('click', delImage, false);
newedit.addEventListener('click', showModal, false);

.
.
.

function showModal(){
    var edit_id = this.getAttribute("dataset-editid");
    var image_id = document.getElementById('img-'+edit_id);
    var thisImage = image_id.src;
    $('#'+edit_id).click(function(){
        $("#cropImagePop").modal();
    });
    console.log(edit_id);
    console.log('image source: ' + image_id);
    var themodal = document.getElementById('cropImagePop');
    var theimage = document.getElementById('cropimage');
    var instance = new Croppie(theimage, {
        viewport: { width: 300, height: 300 },
        boundary: { width: 900, height: 600 },
        showZoomer: true,
        enableResize: true,
        url: thisImage
    });

}

当我单击任意给定图片的动态“编辑”按钮时,模态会打开,但是照片确实很大(不在模态内),并且没有要裁剪的边框。

这里是一个小提琴:https://jsfiddle.net/noz2eb3y/

也-我绝不是嫁给Croppie-如果有人拥有一个很棒的(正在工作!)JavaScript库,他们知道该库可以缩放/旋转/裁剪图像-我全是耳朵!

1 个答案:

答案 0 :(得分:0)

要回答您的问题:是可以的。

模式窗口的问题是因为您忘记添加croppie css参考。

我在此fiddle中修复了该问题,还向裁剪按钮添加了一个功能,以更新源元素。

请参见以下示例:

$('#cropImageBtn').click(function(){
  instance.result('base64').then(function(base64) {
    image_id.src = base64;
    cleanModal();
  });
});
$('#closeImageBtn').click(function(){
    cleanModal();
});
function cleanModal()
{
  instance.destroy();
  $("#cropImagePop").modal("hide");
}

要上传图像,需要执行的下一步。

  1. 看看jquery.ajax
  2. 将base64编码的数据发布到您的服务器
  3. 解码base64编码数据
  4. 保存图像文件

我还建议改善您的代码(有点混乱)。