Javascript: Get the image blob Object through the image url

Source: Internet
Author: User
Why?
  1. Users do not need to download images and then upload them through input file;
  2. The chrome plug-in can directly right-click the image on the page and upload the image directly;
  3. All to increase user experience!
Ideas
  1. Request an image through ajax to obtain the binary data of the image
  2. Combine Uint8Array and BlobBuilder to obtain the blob Object of the image.
  3. Added fileName and fileType, disguised as a File object
Implementation Code
/*** Convert the string conforming to the byte stream to the Blob Object ** @ param {String} data * @ return {Blob} * @ api public */function binaryToBlob (data) {var bb = new BlobBuilder (); var arr = new Uint8Array (data. length); for (var I = 0, l = data. length; I https://developer.mozilla.org/En/XMLHttpRequest/Using_XMLHttpRequest#Receiving_binary_data // XHR binary charset opt by Marcus Granado 2006 [http://mgran.blogspot.com] r. overrideMimeType ('text/plain; charset = x-user-defined'); r. send (null); var blob = binaryToBlob (r. responseText); blob. name = blob. fileName = url. substring (url. lastIndexOf ('/') + 1); blob. fileType = "image/jpeg"; // "image/octet-stream"; return blob ;}; /*** convert dataUrl to Blob Object ** @ param {String} dataurl * @ return {Blob} * @ api public */function dataUrlToBlob (dataurl) {// data: image/jpeg; base64, xxxxxx var datas = dataurl. split (',', 2); var blob = binaryToBlob (atob (datas [1]); blob. fileType = datas [0]. split (';') [0]. split (':') [1]; blob. name = blob. fileName = 'pic. '+ blob. fileType. split ('/') [1]; return blob ;};
Read more
  • Https://developer.mozilla.org/en/DOM/Blob
  • Http://www.w3.org/TR/FileAPI/#dfn-Blob
  • Https://developer.mozilla.org/En/XMLHttpRequest/Using_XMLHttpRequest#Receiving_binary_data
  • Http://www.nihilogic.dk/labs/canvas2image/
Love

^_^ Hope this article will be useful to you

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.