How can you encode a string to Base64 in JavaScript?

前端 未结 26 3876
梦如初夏
梦如初夏 2020-11-21 04:02

I have a PHP script that can encode a PNG image to a Base64 string.

I\'d like to do the same thing using JavaScript. I know how to open files, but I\'m not sure how

26条回答
  •  情话喂你
    2020-11-21 05:08

    if you need to encode HTML image object, you can write simple function like:

    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);  
      var dataURL = canvas.toDataURL("image/png");  
      // escape data:image prefix
      return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");  
      // or just return dataURL
      // return dataURL
    }  
    

    To get base64 of image by id:

    function getBase64ImageById(id){  
      return getBase64Image(document.getElementById(id));  
    } 
    

    more here

提交回复
热议问题