javascript - Drag and drop image convert to Base64 - Stack Overflow

I require the following functionality in my website. Everything has to be done on the client (javascrip

I require the following functionality in my website. Everything has to be done on the client (javascript or any javascript library).

I have an image in my local machine, drag and drop it in the browser. Without any request to the server, the javascript has to convert this image as base64.

I have a code for converting the image to base64 on the client side, but this one requires HTTP URL. What I need is, the image needs to be uploaded from local.

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('', function(dataUrl) {
  console.log('RESULT:', dataUrl)
})

I require the following functionality in my website. Everything has to be done on the client (javascript or any javascript library).

I have an image in my local machine, drag and drop it in the browser. Without any request to the server, the javascript has to convert this image as base64.

I have a code for converting the image to base64 on the client side, but this one requires HTTP URL. What I need is, the image needs to be uploaded from local.

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./avatar/d50c83cc0c6523b4d3f6085295c953e0', function(dataUrl) {
  console.log('RESULT:', dataUrl)
})
Share Improve this question asked Jan 14, 2019 at 13:45 NageswaranNageswaran 7,71114 gold badges59 silver badges77 bronze badges 7
  • I have used a canvas element for drag and drop in the browser. If you use the toDataUrl method on the canvas, you should pass "image/png" as the parameters, not a URL. Like this: var imageData = image.toDataURL("image/png"); imageData = imageData.replace('data:image/png;base64,', ''); Note that I had to replace 'data:image/png;base64' with an empty string when submitting the base 64 string to the server. – iCode Commented Jan 14, 2019 at 13:58
  • @iCode: Can you give some example? – Nageswaran Commented Jan 14, 2019 at 14:01
  • Are you already using a <canvas> element? – iCode Commented Jan 14, 2019 at 14:06
  • Nope, if it is needed, I can use – Nageswaran Commented Jan 14, 2019 at 14:16
  • I updated with an answer below. I've linked to a JS Fiddle which you can use to test drag/drop onto a canvas element and modify to fit your needs. – iCode Commented Jan 14, 2019 at 15:29
 |  Show 2 more ments

1 Answer 1

Reset to default 5

I have expanded on existing code in this JS Fiddle which allows Copy/Paste of images to include Drag/Drop behavior: http://jsfiddle/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./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");

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745480907a4629551.html

相关推荐

  • javascript - Drag and drop image convert to Base64 - Stack Overflow

    I require the following functionality in my website. Everything has to be done on the client (javascrip

    3小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信