How to Get Base64 String From Image an Image JavaScript

Sathish Nadarajan
 
Solution Architect
January 20, 2021
 
Rate this article
 
Views
1836

In one of the recent requirements, needed to get the Base64 string from the Image using JavaScript.  Though it seems a simple one, there are a couple of settings which wanted to share with the community.

It doesn’t require much explanation.  The below code snippets are self-explanatory.

<div class="container" style="padding: 8px;">

                <img id="1" crossOrigin="anonymous" class="myimages" src="https://source.unsplash.com/600x600/?sig=1" alt="1.jpg"/>
                <img id="2" crossOrigin="anonymous" class="myimages" src="https://source.unsplash.com/600x800/?sig=12" alt="1.jpg"/>
                <img id="3" crossOrigin="anonymous" class="myimages" src="https://source.unsplash.com/800x600/?sig=71" alt="1.jpg"/>
                <img id="4" crossOrigin="anonymous" class="myimages" src="https://source.unsplash.com/600x600/?sig=40" alt="1.jpg"/>
                <img id="5" crossOrigin="anonymous" class="myimages" src="https://source.unsplash.com/600x600/?sig=32" alt="1.jpg"/>

            </div>
The Attribute crossOrigin should be anonymous when we deal with external Image URLs as above.

When the Office is Ready, we are assigning a Click Event for the Images.

Office.onReady(function () {
        // Office is ready
        $(document).ready(function () {
            // The document is ready
             
            $('.myimages').click(insertImage);
        });
    });

And the Function getBase64String is as below.

function getBase64String(id) {

        console.log(id);

        var img = document.getElementById($(id)[0].currentTarget.id);

        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        canvas.width = img.naturalWidth;
        canvas.height = img.naturalHeight;

        ctx.drawImage(img, 0, 0);

        var base64string = canvas.toDataURL().split(',')[1];
return base64string;
}
The width and height of the canvas should be image’s natural width and height.  This will give you the Original Image width and height.

 

Hope this is simple and useful for someone who looks for same kind of requirement.

 

Happy Coding,

Sathish Nadarajan.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Leave a comment