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 (5)

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 :)
    • GFG,
      Usage:
      btoa(data) - Converts data to STRING and encodes it to Base64
      Arguments:
      data (required string) - Text or binary content that you want to encode
      Return Values:
      STRING - On success, it returns the Base64 value, typically longer by about 33% than data
      Exceptions:
      On failure the function may throw one of the following exceptions:

      InvalidCharacterError: String contains an invalid character
      TypeError: Not enough arguments to Window.btoa
  • 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?
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.

Loading...