DEV Community

loading...

How to base64 encode an image in javascript

Migsar Navarro
Not sure anymore... I like tech but not that much.
・2 min read

A few days ago I was looking for a way to quickly put an image as a string to send it in a message. I remembered that it was possible to use base64 for that but I did not remember the exact procedure.

I had to get bits from different stackoverflow answers to get it working. I decided to write this article to save you a few minutes.

function imgToBase64(img) {
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');
  canvas.width = img.width;
  canvas.height = img.height;

  // I think this won't work inside the function from the console
  img.crossOrigin = 'anonymous';

  ctx.drawImage(img, 0, 0);

  return canvas.toDataURL();
}
Enter fullscreen mode Exit fullscreen mode

Let's try it:

  1. Here is a beautiful photo of Xochimilco, in Mexico City, Mexico taken by Jeremy Lishner on Unsplash. You can follow the link, if you want, but I included the image so you don't have to leave this page.

Photo by Jeremy Lishner on Unsplash

  1. Open the console (Ctrl + Shift + I).
  2. Paste the code. We will have imgToBase64 available as a function.
  3. Click the pick icon on the top left (Ctrl + Shift + C) and select the image. Now you will have a reference to the DOMElement with $0.
  4. Type copy(imgToBase64($0)). Now you have the image string in the clipboard, ready to paste somewhere else.

Sometimes you get an error SecurityError: The operation is insecure., this is related to the crossOrigin attribute, you can manually change the value to anonymous $0.crossOrigin = 'anonymous' and repeat step 4.

Tip: You can test the base64 image string you just created by pasting it in the url of a browser tab. Like this:
Alt Text

That's it... I hope you find it useful.

Discussion (2)

Collapse
dantenl profile image
dante-nl

I get "Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLImageElement or SVGImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap or OffscreenCanvas)'" when I use it like this: console.log(imgToBase64(img))

Collapse
jackkeller profile image
Jack Keller

Works pretty good, I've been looking for an idea for a small json based API that could store images as base64!