拖放图像转换为 Base64

Nag*_*ran 5 javascript browser jquery drag-and-drop image

我的网站需要以下功能。一切都必须在客户端(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)
})
Run Code Online (Sandbox Code Playgroud)

iCo*_*ode 5

我扩展了这个 JS Fiddle中的现有代码,它允许复制/粘贴图像以包括拖/放行为: http://jsfiddle.net/wrv369/cbqe39L5/

我在 Chrome 浏览器中测试成功,但没有在 Firefox、IE 或任何其他浏览器中测试。

我使用 HTML 5 画布元素和 JavaScript 来实现拖/放。在画布上,通过调用 来防止拖拽放置e.preventDefault();事件的默认操作非常重要。否则,拖放只会在新选项卡/窗口中打开图像。

这是一个完整的例子。

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>
Run Code Online (Sandbox Code Playgroud)

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: /sf/answers/1217076241/
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();
  //}
});
Run Code Online (Sandbox Code Playgroud)

如果您查看 saveButton 单击处理程序,您可以了解如何通过调用此行代码中的 .toDataURL() 函数来获取 Base 64 图像字符串:

var imageData = image.toDataURL("image/png");
Run Code Online (Sandbox Code Playgroud)

  • 哇,这太棒了!非常感谢!我编辑了代码并使其更可重用:http://jsfiddle.net/rwhal06/8Lv59zqt/ (2认同)