JS image to base64 return string - javascript

I have code that works fine
function convertImgToBase64URL(url, callback, outputFormat){
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function(){
var canvas = document.createElement('CANVAS'),
ctx = canvas.getContext('2d'), dataURL;
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
canvas = null;
};
img.src = url;
}
convertImgToBase64URL('/img/logo.png', function(base64Img){
console.log(base64Img);
});
But I need to get the result into a variable
convertImgToBase64URL('/img/logo.png', function(base64Img){
var test = base64Img;
});
alert(test);
Any idea how to pass the result to a variable?

Related

Unable to convert png image to base64encoded string

This piece of code below is supposed to convert the raw image to base64 string.
let base1="";
let base2="";
let base3="";
let base64String="";
var img=new Image();
var img1=new Image();
var img2=new Image();
img.src='Screenshot (1).png';
img1.src='Screenshot (2).png';
img2.src='Screenshot (3).png';
var reader = new FileReader();
reader.onload = function () {
base64String = reader.result.replace("data:", "")
.replace(/^.+,/, "");
}
reader.readAsDataURL(img);
base1=base64String;
reader.readAsDataURL(img1);
base2=base64String;
reader.readAsDataURL(img2);
base3=base64String;
But when I execute the code, I get the following error:
Uncaught TypeError: Failed to execute 'readAsDataURL' on 'FileReader':
parameter 1 is not of type 'Blob'.
Why is that? Please help me fix this.
Because readAsDataURL expects the parameter as Blob. Best method will be to convert to base64 data url using canvas
let base1="";
let base2="";
let base3="";
let base64String="";
var img=new Image();
var img1=new Image();
var img2=new Image();
img.onload = function() {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
base1 = canvas.toDataURL();
}
img.src='Screenshot (1).png';
img1.onload = function() {
var canvas = document.createElement("canvas");
canvas.width = img1.width;
canvas.height = img1.height;
ctx = canvas.getContext('2d');
ctx.drawImage(img1, 0, 0);
base2 = canvas.toDataURL();
}
img1.src='Screenshot (2).png';
img2.onload = function() {
var canvas = document.createElement("canvas");
canvas.width = img2.width;
canvas.height = img2.height;
ctx = canvas.getContext('2d');
ctx.drawImage(img2, 0, 0);
base2 = canvas.toDataURL();
}
img2.src='Screenshot (3).png';
The canvas.toDataURL() without param will generate a data url of type png if if the img src is a jpg

Image dimensions not reflected correctly

I am trying to get the base64 of some images in Javascript and was using this function:
function getBase64Image(img) {
return new Promise((data) => {
var canvas = document.createElement("canvas");
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
data(canvas.toDataURL("image/png").replace(/^data:image\/(png|jpg|jpeg);base64,/, ""))
})
}
Then I call the function to load in the image using:
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function () {
getBase64Image(this).then(data => {})
}
img.src = wha[1][0]
If I look at the naturalWidth of the image (96px), it is different from the actual image itself (640px). I had been looking at other methods of getting base64 from an image but they also return the same results.

Image is not getting displayed when adding image to a PDF

I am trying to create PDF with Image. I have URL of Image as below:
var url = "https://firebasestorage.googleapis.com/v0/b/dicom-poc.appspot.com/o/images%2FNiouCzjBYna8Wx1VO2x3UST5tDc2%2F2020-10-07%2F05%3A03%3A58%2Fvisualization%2FL-CC.png?alt=media&token=dce8859a-3427-432b-8176-590e9569aad9"
and my code is here:
var pdf = new jsPDF();
var img = new Image();
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
img = document.createElement('img');
img.src = url;
img.onload = function(){
canvas.height = img.height;
canvas.width = img.width;
var dataURL = canvas.toDataURL('image/png')
var base64 = dataURL.replace(/^data:.+;base64,/, '');
pdf.text("Hi");
pdf.addImage(base64,'PNG',5,5,50,50);
pdf.save("download.pdf");
}
After running above code PDF is getting downloaded successfully with text "Hi" but image is not there.
I have tried multiple solutions suggested by people but no result.
Could you please guide me for same.
Thanks in advanace!
You did not draw anything on the canvas.
var pdf = new jsPDF();
var img = new Image();
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
img = document.createElement('img');
img.src = url;
img.onload = function(){
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img, img.width, img.width);
var dataURL = canvas.toDataURL('image/png')
var base64 = dataURL.replace(/^data:.+;base64,/, '');
pdf.text("Hi");
pdf.addImage(base64,'PNG',5,5,50,50);
pdf.save("download.pdf");
}

Convert canvas to base64 error

Result convert is null png image, pls help me
var img = new Image();
img.src = 'http://advs.jp/cp/barcode/code128.cgi?nt=1&height=80&c=Z103B5-190-311378&.png';
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
var dataurl = canvas.toDataURL().replace("data:image/jpeg;base64,", "");
localStorage.setItem("img", dataurl);
$('#bannerImg').attr('src', dataurl);
<img id="bannerImg" src="" alt="Banner Image" width="100%" height="200px" alt="Embbed Image"/>
<canvas id="myCanvas"></canvas>
You have to include everything (drawing to canvas + reading from it + setting this elsewhere) in the onload event of the image. It doesn't work on this snippet (the call to toDataURL) due to a cross-domain issue, but it shall work on your website.
An explanation of why it doesn't work here the call to toDataURL
var imgCanvas = function() {
var img = new Image();
//Wait for image to load before doing something with content
img.onload = function() {
var canvas = document.getElementById("myCanvas");
//Set canvas size to fit the image
canvas.style.height = img.height + 'px';
canvas.style.width = img.width + 'px';
//Draw the image in canvas
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
//Get a dataurl representation of the image where the image itself is in BASE64
var dataurl = canvas.toDataURL();
//Store it in localStorage
localStorage.setItem("img", dataurl);
//Show image from localStorage
//Need jQuery to use this line instead of next one : $('#bannerImg').attr('src', localStorage.getItem("img"));
document.getElementById('bannerImg').setAttribute('src', localStorage.getItem("img"));
};
img.src = 'http://advs.jp/cp/barcode/code128.cgi?nt=1&height=80&c=Z103B5-190-311378&.png';
};
imgCanvas();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Canvas:<br>
<canvas id='myCanvas'></canvas>
<br><br>
Image from dataurl:<br>
<img id='bannerImg'>
Use document.getElementById('bannerImg').setAttribute('src', dataurl); instead.
var showImage = function() {
var img = new Image;
img.onload = function() {
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataurl = canvas.toDataURL();
localStorage.setItem("img", dataurl);
document.getElementById('bannerImg').setAttribute('src', dataurl);
};
img.src = 'http://advs.jp/cp/barcode/code128.cgi?nt=1&height=80&c=Z103B5-190-311378&.png';
};
showImage();
Example: https://jsfiddle.net/atg5m6ym/6152/

Can't use canvas method putImageData

I have following code:
var img = new Image();
canvas = document.getElementById("c");
ctx = canvas.getContext('2d')
canvas2 = document.getElementById("c2");
ctx2 = canvas2.getContext('2d')
img.onload = function () {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img,0,0);
};
img.src = 'mwq.gif';
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
ctx2.putImageData(imageData, 0, 0);
and i get image on first canvas element, when i check in console there is imageData, with width, lenght and pixel array, but somehow i can't get that image on another canvas element. I dont think there are typos, i rewrote same code several times, and at the end i stripped it to most minimal version without pixel manipulation, but it's still not working.
Your code isn't called in the onload callback, it's executed before the image is loaded so there is nothing to put.
You could change it to
var img = new Image();
canvas = document.getElementById("c");
ctx = canvas.getContext('2d')
canvas2 = document.getElementById("c2");
ctx2 = canvas2.getContext('2d')
img.onload = function () {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img,0,0);
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
ctx2.putImageData(imageData, 0, 0);
};
img.src = 'mwq.gif';

Categories