拖放图像转换为Base64

时间:2019-01-14 13:45:15

标签: javascript jquery image browser drag-and-drop

我在我的网站上需要以下功能。一切都必须在客户端(javascript或任何javascript库)上完成。

我在本地计算机上有一个图像,将其拖放到浏览器中。没有对服务器的任何请求,javascript必须将该图像转换为base64。

我有一个用于在客户端将图像转换为base64的代码,但这需要HTTP URL。我需要的是,该图像需要从本地上传。

function toDataURL(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.onload = function() {
    var reader = new FileReader();
    reader.onloadend = function() {
      callback(reader.result);
    }
    reader.readAsDataURL(xhr.response);
  };
  xhr.open('GET', url);
  xhr.responseType = 'blob';
  xhr.send();
}

toDataURL('https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0', function(dataUrl) {
  console.log('RESULT:', dataUrl)
})

1 个答案:

答案 0 :(得分:1)

我对this JS Fiddle中的现有代码进行了扩展,该代码允许“复制/粘贴”图像包含“拖放”行为: http://jsfiddle.net/wrv369/cbqe39L5/

我在Chrome浏览器中成功进行了测试,但未在Firefox,IE或任何其他浏览器中进行测试。

我正在使用HTML 5 canvas元素和JavaScript来实现拖放。在画布上,通过调用e.preventDefault();来防止 dragover drop 事件的默认操作很重要。否则,拖放操作只会在新标签页/窗口中打开图像。

这是一个完整的例子。

HTML:

<div id="instructions">
  Method 1:<br /> 1. Copy image data into clipboard, or press Print Screen <br /> 2. Press Ctrl+V (page/iframe must be focused): <br /><br /> Method 2:<br /> 1. Drag and drop an image onto the canvas
</div>
<br /><br />
<canvas style="border:1px solid grey;" id="my_canvas" width="300" height="300"></canvas>

JavaScript:

var CLIPBOARD = new CLIPBOARD_CLASS("my_canvas", true);

/**
 * image pasting into canvas
 * 
 * @param {string} canvas_id - canvas id
 * @param {boolean} autoresize - if canvas will be resized
 */
function CLIPBOARD_CLASS(canvas_id, autoresize) {
  var _self = this;
  var canvas = document.getElementById(canvas_id);
  var ctx = document.getElementById(canvas_id).getContext("2d");

  //handlers
  document.addEventListener('paste', function(e) {
    _self.paste_auto(e);
  }, false);

  /* events fired on the drop targets */
  document.addEventListener("dragover", function(e) {
    // prevent default to allow drop
    e.preventDefault();
  }, false);
  document.addEventListener('drop', function(e) {
    // prevent default action (open as link for some elements)
    //debugger;
    e.preventDefault();
    var items = e.dataTransfer.items;
    for (var i = 0; i < items.length; i++) {
      if (items[i].type.indexOf("image") !== -1) {
        document.getElementById("instructions").style.visibility = "hidden";
        //image
        var blob = items[i].getAsFile();
        var URLObj = window.URL || window.webkitURL;
        var source = URLObj.createObjectURL(blob);
        _self.paste_createImage(source);
      }
    }
  });

  //on paste
  this.paste_auto = function(e) {
    if (e.clipboardData) {
      var items = e.clipboardData.items;
      if (!items) return;

      //access data directly
      for (var i = 0; i < items.length; i++) {
        if (items[i].type.indexOf("image") !== -1) {
          //image
          var blob = items[i].getAsFile();
          var URLObj = window.URL || window.webkitURL;
          var source = URLObj.createObjectURL(blob);
          this.paste_createImage(source);
        }
      }
      e.preventDefault();
    }
  };
  //draw pasted image to canvas
  this.paste_createImage = function(source) {
    //debugger;
    var pastedImage = new Image();
    pastedImage.onload = function() {
      if (autoresize == true) {
        //resize
        canvas.width = pastedImage.width;
        canvas.height = pastedImage.height;
      } else {
        //clear canvas
        ctx.clearRect(0, 0, canvas.width, canvas.height);
      }
      ctx.drawImage(pastedImage, 0, 0);
    };
    pastedImage.src = source;
  };
}

// detect blank canvas: https://stackoverflow.com/a/17386803/177416
function isCanvasBlank(canvas) {
  var blank = document.createElement('canvas');
  blank.width = canvas.width;
  blank.height = canvas.height;

  return canvas.toDataURL() === blank.toDataURL();

}

document.getElementById("saveButton").addEventListener("click", function() {
  debugger;
  var form = document.getElementById("myForm");
  //if (form.valid()) {
    var image = document.getElementById("my_canvas");
    if (!isCanvasBlank(image)) {
      var imageData = image.toDataURL("image/png");
      imageData = imageData.replace('data:image/png;base64,', '');
      document.getElementById("imageData").value = imageData;
    } else {
      // Pass null, otherwise the POST will submit { id = "imageData" } for this field.
      document.getElementById("imageData").value = null;
    }
    //form.submit();
  //}
});

如果您查看saveButton单击处理程序,则可以在以下代码行中看到如何通过调用.toDataURL()函数获取基本的64位图像字符串:

var imageData = image.toDataURL("image/png");