拖放圖片轉Base64 (Drag and drop image convert to Base64)


問題描述

拖放圖片轉Base64 (Drag and drop image convert to Base64)

我的網站需要以下功能。一切都必須在客戶端(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:

I have expanded on existing code in this JS Fiddle which allows Copy/Paste of images to include Drag/Drop behavior: http://jsfiddle.net/wrv369/cbqe39L5/

I tested this in the Chrome browser with success, but did not test in Firefox, IE, or any other browser.

I'm using the HTML 5 canvas element and JavaScript to implement drag/drop. On the canvas, it's important to prevent the default action for the dragover and drop events by calling e.preventDefault();. Otherwise drag/drop will simply open the image in a new tab/window.

Here's a full example.

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();
  //}
});

If you look at the saveButton click handler, you can see how to get the base 64 image string with a call to the .toDataURL() function in this line of code:

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

(by NageswaraniCode)

參考文件

  1. Drag and drop image convert to Base64 (CC BY‑SA 2.5/3.0/4.0)

#jquery #Browser #javascript #image #drag-and-drop






相關問題

讓 jQuery 與 Netscape 7 和 8 一起工作 (Getting jQuery to work with Netscape 7 and 8)

使用 Jquery 的 mvc3 搜索結果 (mvc3 search results with Jquery)

從嵌套的 jquery 函數返回一個值 (Return a value from nested jquery function)

Mencocokkan lebar divisi dengan jquery (Matching division widths with jquery)

無法在 jQuery AJAX 中多次生成點擊事件 (unable to generate click event more than once in jQuery AJAX)

使用雙引號格式並用逗號分隔元素數組 (Implode an element array with double quote format and separated by comma)

選擇不更新 (Select doesn't update)

chrome中帶有省略號的多行文本問題 (issue with multiline text with ellipsis in chrome)

AJAX/PHP/JS - 無法將頁面內容加載到容器中 (AJAX/PHP/JS - Cannot load page content into container)

使用 jQuery 將文本插入 textarea (Insert text into textarea with jQuery)

滾動到頁面底部,僅當用戶在 DOM 操作之前已經位於底部時 (Scroll to bottom of page, only if the user already was at the bottom before DOM manipulation)

如何設置單選按鈕的樣式,使其看起來像普通的可點擊按鈕? (How do I style a radio button to look like a normal clickable button?)







留言討論