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();
}
Let's try it:
- 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.
- Open the console (Ctrl + Shift + I).
- Paste the code. We will have
imgToBase64
available as a function. - 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
. - 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:
That's it... I hope you find it useful.
Top comments (2)
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))
Works pretty good, I've been looking for an idea for a small json based API that could store images as base64!