JS How to convert "online picture resources" to "base64"

Source: Internet
Author: User
Tags base64



When realizing the function of Html2canvas, it is found that "picture cross-domain" is not supported, which is a headache;



Accidentally found that if the "online picture resources" converted to Base64, with Base64 rendering, so that the perfect solution to the problem;



Because the picture is cross-domain, we need to add a piece of code in the conversion process to support cross-domain;


" * ";





The complete code is as follows:


function getBase64Image (img) {
     var canvas = document.createElement ("canvas");
     canvas.width = img.width;
     canvas.height = img.height;
     var ctx = canvas.getContext ("2d");
     ctx.drawImage (img, 0, 0, img.width, img.height);
     var dataURL = canvas.toDataURL ("image / png"); // optional other values image / jpeg
     return dataURL;
}

function main (src, cb) {
     var image = new Image ();
     image.src = src;
     image.crossOrigin = "*"; // Support cross-domain image
     image.onload = function () {
         var base64 = getBase64Image (image);
         cb && cb (base64);
     }
}

main (‘http: //wwww.test/test.png’, function (base64) {
     console.log (base64);
}); 

Currently, the types supported by the Data URI scheme are:
Data :, Text
data:text/plain, Text data
data:text/html,html Code
data:text/html;base64,base64 encoded HTML code
DATA:TEXT/CSS,CSS Code
data:text/css;base64,base64 coded CSS code
Data:text/javascript,javascript Code
data:text/javascript;base64,base64 encoded JavaScript code
DATA:IMAGE/GIF;BASE64,BASE64 encoded GIF image data
DATA:IMAGE/PNG;BASE64,BASE64 encoded PNG image data
DATA:IMAGE/JPEG;BASE64,BASE64 encoded JPEG image data
data:image/x-icon;base64,base64 encoded icon image data


JS How to convert "online picture resources" to "base64"


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.