Hi @Muhammad Afzal ,
To ge image content, you will need to create a canvas element with the correct dimensions and copy the image data with the drawImage function. Then you can use the toDataURL function to get a data: url that has the base-64 encoded image. You could refer to this article for more: https://stackoverflow.com/questions/934012/get-image-data-url-in-javascript
function getBase64Image(img) {
// Create an empty canvas element
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
// Copy the image contents to the canvas
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
// Get the data-URL formatted image
// Firefox supports PNG and JPEG. You could check img.src to
// guess the original format, but be aware the using "image/jpg"
// will re-encode the image.
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
After you get the image content , you could use jsom to create a file in the Images library.
function createfile (){
var clientContext;
var oWebsite;
var oList;
var fileCreateInfo;
//get the image tag
var img=document.getElementById("myImage");
var fileContent=getBase64Image(img);
console.log(fileContent);
clientContext = new SP.ClientContext.get_current();
oWebsite = clientContext.get_web();
oList = oWebsite.get_lists().getByTitle("Images");
fileCreateInfo = new SP.FileCreationInformation();
fileCreateInfo.set_url("image.jpg");
fileCreateInfo.set_content(fileContent);
this.newFile = oList.get_rootFolder().get_files().add(fileCreateInfo);
clientContext.load(this.newFile);
clientContext.executeQueryAsync( Function.createDelegate(this, successHandler), Function.createDelegate(this, errorHandler));
function successHandler(){
console.log("FILE CREATED!");
}
function errorHandler(){
console.log("File Creation Failed: " + arguments[1].get_message());
}
}
On button click call the function:
If an Answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.