Simple answer is no if this needs to be done on client side. The canvas element is the only way to convert an image to bitmap data or data-uris (and even then security restriction may apply preventing this).

You can maybe get around this using Flash but of course that would require the client to have Flash installed.

Or setting up an external web service where you can upload the image and have it return the data you need.

For IE8 and lower there are no options out of the box (exCanvas gives you canvas drawing capabilities but can't provide bitmap data which is needed here). Basically, for IE8 you will need a server.

Answer from user1693593 on Stack Overflow
🌐
Talkerscode
talkerscode.com › howto › convert-image-url-to-base64-javascript-without-canvas.php
Convert Image URL To Base64 JavaScript Without Canvas
At that time the result attribute contains the data as a data, URL representing the files data as base64 encoded string. Here we sets image url, function with parameter at last with the method ‘getimgBase64’ then printed on console when result get returns from function definition. In this method we passing that image link as ‘url’ and function as ‘callback’ within this we creating XMLHttpRequest object ‘xhr’.
Discussions

javascript - Convert an image to base64 without using HTML5 Canvas - Stack Overflow
I would load each image in javascript, then use canvas and toDataUrl() to get the base64 data. Then, instead of passing the URL to the UserControl and have it do all the leg work, I pass the base64 data as a instead. Then it quickly converts that data back to the image. More on stackoverflow.com
🌐 stackoverflow.com
javascript - Convert image from url to Base64 - Stack Overflow
Using an Image File, I am getting the url of an image, that needs be to send to a webservice. From there the image has to be saved locally on my system. The code I am using: var imagepath = $("# More on stackoverflow.com
🌐 stackoverflow.com
How to get base64 image data without call canvas toDataURL? - Stack Overflow
I'm on a project which requires to support ie9 or ie10. I'm using d3.js for data visualization. Now I need to provide a function to export the chart as pdf. I have been investigate into possible More on stackoverflow.com
🌐 stackoverflow.com
javascript - Convert image to base64 without server - Stack Overflow
I'm using the Pinterest Javascript SDK to try and create a pin. The parameters to set the image is 1 of either; image - Upload the image you want to pin using multipart form data image_url - The... More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 2
1

A canvas doesn't hold (for example) a jpg. A jpg is lossy. When you load it into canvas, it gets 'unpacked'. When you use a built-in canvas method to output a dataURL, it will first re-compress the raw canvas-data (32 bit per pixel inc alpha) to the (lossy-level depending on internal paramaters) format you have chosen as output, then convert that data to base64.

What I'm trying to say here is, that canvas would not produce a true base64 encoding of the original file; instead it would produce a base64 encoding of the canvas-content (one of canvas' supported output formats). In yet other words: you are not base64-encoding the original binary.

That being said and explained.. there is more.. you might stumble on cross-site security problems inside the browser (assuming you want to be able to feed any URL).

Thus the solution, solving both problems above (also employed by the website you referenced), is to pass the URL (or the bare text entered or file uploaded) to the server where the server gets the image (data) and base64 encodes it (the actual original binary) and passes it back to the client(browser) (for example via AJAX/JSON/etc.).

However, you also say that you are "working solely in javascript without an HTML page". That's kind of vague. In my answer above I assumed a browser (as host) anyway (otherwise you would have mentioned node.js (or something like that) and you'd have gotten error messages about document). If however you do use node, then there is probably something available to download the binary contents from an URL (which you then pass through your javascript implementation of base64 (which again is probably already available in node.js)).

2 of 2
0

The site at most likely use serverside technology (ASP, PHP, etc) to download the image and get it's base64 encoding. You cannot reverse engineer something that is executed on the serverside.

If you use clientside technology (like JavaScript) you may run into "Cross-Origin Resource Sharing"-problems.

The code you have supplied works as it should and you can see this by executing the following 2 calls. Please note that Wikipedia allows resource sharing while jshell.net (JSFiddle) does not - so check you console log for the "Cross-Origin Resource Sharing"-error message.

// Works fine:
convertImgToBase64("http://upload.wikimedia.org/wikipedia/commons/4/4a/Logo_2013_Google.png", function(data){alert(data)});

// Does not work due to "Cross-Origin Resource Sharing"
convertImgToBase64("http://jsfiddle.net/img/logo.png", function(data){alert(data)});
🌐
GitHub
gist.github.com › metrofun › 5536671
Script to convert image into base64, using xhr2 without canvas. Therefore it is possible to convert images from another domains, using CORS. · GitHub
Script to convert image into base64, using xhr2 without canvas. Therefore it is possible to convert images from another domains, using CORS. - getBase64FromImage.js
🌐
GitHub
gist.github.com › oliyh › db3d1a582aefe6d8fee9
Convert an image url to a data URI without canvas · GitHub
(require '[ajax.protocols :as pr]) ;; effecting with re-frame-http-fx {:http-xhrio {,,, :response-format {:content-type "image/png" :description "PNG image" :read pr/-body :type :arraybuffer} :on-success [::my-handler]} (rf/reg-event-db ::my-handler (fn [db [_ response]] (assoc db :thing (->> response (js/Uint8Array.) (js/String.fromCharCode.apply nil) (js/btoa) (str "data:image/png;base64,")))))
🌐
Stack Overflow
stackoverflow.com › questions › 13182887 › convert-an-image-to-base64-without-using-html5-canvas
javascript - Convert an image to base64 without using HTML5 Canvas - Stack Overflow
I would load each image in javascript, then use canvas and toDataUrl() to get the base64 data. Then, instead of passing the URL to the UserControl and have it do all the leg work, I pass the base64 data as a <PARAM> instead.
Find elsewhere
🌐
FRONT
front.design › wp-content › uploads › dt5on8me › 2puiv4.php
convert image url to base64 javascript without canvas
Create a canvas, load your image into it and then use toDataURL() to get the base64 representation (actually, it’s a data: URL but it contains the base64-encoded image). I have two variables holding sources of images - pic1, pic2 and a global variable basePic for holding base64 string.
🌐
Stack Overflow
stackoverflow.com › questions › 27718684 › how-to-get-base64-image-data-without-call-canvas-todataurl
How to get base64 image data without call canvas toDataURL? - Stack Overflow
... svgElement = $('svg').get(0); ... DOMURL = window.URL || window.webkitURL || window; url = DOMURL.createObjectURL(new Blob([str], {type: 'image/svg+xml;charset=utf-8'}));...
🌐
JSFiddle
jsfiddle.net › handtrix › YvQ5y
Image to Base64 - JSFiddle - Code Playground
CSS Import: @import url('@jsfiddle/[username]/[fiddle].css')
🌐
Stack Overflow
stackoverflow.com › questions › 46749919 › convert-image-to-base64-without-server
javascript - Convert image to base64 without server - Stack Overflow
I have tried both the image and image_url parameters to send that value (imageUrl) through, but because the value resolves to a place on my hard drive, it doesn't work (probably expectantly). So now I have to try and figure out how to use the image_base64 option, which means I need to convert the image to base64 on the users machine.
🌐
GitHub
gist.github.com › HereChen › e173c64090bea2e2fa51
convert image to base64 · GitHub
May 14, 2018 - <script type='text/javascript'> function encodeImageFileAsURL() { var filesSelected = document.getElementById("inputFileToLoad").files; if (filesSelected.length > 0) { var fileToLoad = filesSelected[0]; var fileReader = new FileReader(); fileReader.onload = function(fileLoadedEvent) { var srcData = fileLoadedEvent.target.result; // <--- data: base64 var newImage = document.createElement('img'); newImage.src = srcData; document.getElementById("imgTest").innerHTML = newImage.outerHTML; alert("Converted Base64 version is " + document.getElementById("imgTest").innerHTML); console.log("Converted Base64 version is " + document.getElementById("imgTest").innerHTML); } fileReader.readAsDataURL(fileToLoad); } } </script>
Top answer
1 of 9
95

A way to avoid the main HTML to be affected is to create an off-screen canvas that is kept out of the DOM-tree.

This will provide a bitmap buffer and native compiled code to encode the image data. It is straight forward to do:

function imageToDataUri(img, width, height) {

    // create an off-screen canvas
    var canvas = document.createElement('canvas'),
        ctx = canvas.getContext('2d');

    // set its dimension to target size
    canvas.width = width;
    canvas.height = height;

    // draw source image into the off-screen canvas:
    ctx.drawImage(img, 0, 0, width, height);

    // encode image to data-uri with base64 version of compressed image
    return canvas.toDataURL();
}

If you want to produce a different format than PNG (default) just specify the type like this:

return canvas.toDataURL('image/jpeg', quality);  // quality = [0.0, 1.0]

Worth to note that CORS restrictions applies to toDataURL().

If your app is giving only base64 encoded images (I assume they are data-uri's with base64 data?) then you need to "load" the image first:

var img = new Image;

img.onload = resizeImage;
img.src = originalDataUriHere;

function resizeImage() {
    var newDataUri = imageToDataUri(this, targetWidth, targetHeight);
    // continue from here...
}

If the source is pure base-64 string simply add a header to it to make it a data-uri:

function base64ToDataUri(base64) {
    return 'data:image/png;base64,' + base64;
}

Just replace the image/png part with the type the base64 string represents (ie. make it an optional argument).

2 of 9
32

Ken's answer is the right answer, but his code doesn't work. I made some adjustments on it and it now works perfectly. To resize a Data URI :

// Takes a data URI and returns the Data URI corresponding to the resized image at the wanted size.
function resizedataURL(datas, wantedWidth, wantedHeight)
    {
        // We create an image to receive the Data URI
        var img = document.createElement('img');

        // When the event "onload" is triggered we can resize the image.
        img.onload = function()
            {        
                // We create a canvas and get its context.
                var canvas = document.createElement('canvas');
                var ctx = canvas.getContext('2d');

                // We set the dimensions at the wanted size.
                canvas.width = wantedWidth;
                canvas.height = wantedHeight;

                // We resize the image with the canvas method drawImage();
                ctx.drawImage(this, 0, 0, wantedWidth, wantedHeight);

                var dataURI = canvas.toDataURL();

                /////////////////////////////////////////
                // Use and treat your Data URI here !! //
                /////////////////////////////////////////
            };

        // We put the Data URI in the image's src attribute
        img.src = datas;
    }
// Use it like that : resizedataURL('yourDataURIHere', 50, 50);
🌐
Glide Community
community.glideapps.com › ask for help
How to convert glides image url into base 64 without Javascript/Make? - Ask for Help - Glide Community
November 26, 2024 - Every time a user uploads a picture we want to convert it to base64 for one of our integration partners. The Javascript column caches and therefore is too unreliable, while Make ends up being too costly having to also p…
🌐
Tick
pqina.nl › blog › convert-an-image-to-a-base64-string-with-javascript
Convert An Image To A DataURL or Base64 String Using JavaScript - Pqina
In all examples below we assume we already have a <canvas>, <img>, File, or Blob object available. We’ll be converting images to DataURLs, we can use the function below to convert a DataURL to a Base64 string. const getBase64StringFromDataURL = (dataURL) => dataURL.replace('data:', '').replace(/^.+,/, ''); Let’s get started. When the image is a File object or Blob we can use the FileReader API please see this article on converting a file to base64 string or dataURL.
🌐
Jam
jam.dev › utilities › image-to-base64
Image to Base64 Converter | Free, Open Source & Ad-free
Jam's free tool to convert images to Data URI comes in handy when you need to reduce HTTP requests. Convert images to base64 so you can embed them directly into HTML, CSS, or JavaScript.
🌐
Formspree
formspree.io › blog › image-to-base64
How to Convert an Image URL to Base64 | Formspree
August 28, 2024 - Browser-based JavaScript offers a convenient way to convert image URLs to Base64, providing more control and integration within your web application. This method utilizes the Fetch API.
🌐
W3docs
w3docs.com › javascript
How to Convert the Image into a Base64 String Using JavaScript | W3Docs
Note: To extract a raw Base64 string without the data:image/...;base64, prefix, use reader.result.split(',')[1]. Always implement proper error handling (e.g., try...catch or .catch()) for production applications.
🌐
Stack Abuse
stackabuse.com › bytes › converting-images-and-image-urls-to-base64-in-node-js
Converting Images and Image URLs to Base64 in Node.js
August 19, 2023 - In Node.js, converting an image URL to Base64 can be achieved using the request module along with the built-in Buffer class. This Base64 data can then be embedded directly into an HTML image tag, allowing the image to be displayed within the web page without linking to an external file.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-convert-image-into-base64-string-using-javascript
Convert image into base64 string using JavaScript - GeeksforGeeks
February 25, 2026 - <!DOCTYPE html> <html> <head> <title> How to convert image into base64 string using JavaScript ? </title> </head> <body> <input type="file" name="" id="fileId" onchange="imageUploaded()"> <br><br> <button onclick="displayString()"> Display String </button> <script> let base64String = ""; function imageUploaded() { let file = document.querySelector( 'input[type=file]')['files'][0]; let reader = new FileReader(); console.log("next"); reader.onload = function () { base64String = reader.result.replace("data:", "") .replace(/^.+,/, ""); imageBase64Stringsep = base64String; // alert(imageBase64Stringsep); console.log(base64String); } reader.readAsDataURL(file); } function displayString() { console.log("Base64String about to be printed"); alert(base64String); } </script> </body> </html>