Convert image to base64 javascript
There are multiple approaches you can choose from: Show 1. Approach: FileReaderLoad the image as blob via XMLHttpRequest and use the FileReader API (readAsDataURL()) to convert it to a dataURL:
This code example could also be implemented using the WHATWG fetch API:
These approaches:
Browser Support:
2. Approach: CanvasLoad the image into an Image-Object, paint it to a nontainted canvas and convert the canvas back to a dataURL.
In detail Supported input formats:
Supported output formats:
Browser Support:
3. Approach: Images from the local file systemIf you want to convert images from the users file system you need to take a different approach. Use the FileReader API:
In this short tutorial we explore 3 different JavaScript methods to convert an image into a Base64 string. We look at converting a File object or Blob, a canvas element, and an image tag. In all examples below we assume we already have a We’ll be converting images to DataURLs, we can use the function below to convert a DataURL to a Base64 string.
Let’s get started. Image is a File object or BlobWhen the image is a We’ll also use the FileReader API when converting an image tag to a Base64 string. Image is a Canvas elementIf we have a
By default the canvas
outputs to a lossless PNG, we can pass When using
Image is an img elementIf our image is an Alternatively we can draw the image to a canvas and then convert the canvas to an image element, this would be useful if we’re looking for a specific image format. If the image is located on a remote server the CORS configuration of the remote server must allow our local script to access the image. Fetching the image sourceNote that the MIME type returned by remote server in the If the MIME type is incorrect the DataURL will be incorrect as well.
Drawing the image to a canvasDrawing the image to a canvas first allows us to convert it to a different format. Please note that this approach is slower than simply fetching the image An additional caveat is that the canvas element has a maximum size, for some browsers this size limit is very low causing problems when converting the image.
Wrapping upWe converted a |