You need to use readAsDataUrl():
function getBase64(event) {
let me = this;
let file = event.target.files[0];
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
//me.modelvalue = reader.result;
console.log(reader.result);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
Answer from Suresh Kumar Ariya on Stack OverflowYou need to use readAsDataUrl():
function getBase64(event) {
let me = this;
let file = event.target.files[0];
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
//me.modelvalue = reader.result;
console.log(reader.result);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
This is something i have done to upload a profile picture i have also checked for size less than 512KB and then i have posted that image to my API in next function
i have used FileReader() and readAsDataURL() to convert the file to base64
/* On Change Profile image*/
onProfileChange(event:any) {
if(event.target.files && event.target.files[0]) {
if(event.target.files[0].type && event.target.files[0].type.split('/')[0] == ["image"] && event.target.files[0].size <= 512000){
this.file = event.target.files[0];
var reader = new FileReader();
reader.onload = (event:any) => {
this.Image = event.target.result;
}
reader.readAsDataURL(event.target.files[0]);
this.isBrowser = false;
} else {
this.isBrowser = true;
this._toastr.error("Max image upload size is 500KB only");
}
}
}
/*end Of On Change profile Image*/
/*Image api*/
AddImage(event: any){
let data=new FormData();
if(this.file){
data.append('image',this.file);
this._db.Post('api/users/image',data).subscribe(b=>{
if(b.IsResult){
this._toastr.success(b.ResultMsg);
this.getProfileDetail();
this.isBrowser=true;
}
});
}else{
this._toastr.error("Something went wrong");
}
}
Convert image path to base64 in typescript - Stack Overflow
angular - How can I convert image url to base64 string? - Stack Overflow
angular - Typescript convert an image url to base64 encoded string fails - Stack Overflow
Convert image from url to Base64
HTML
<img id="imageid" src="https://www.google.de/images/srpr/logo11w.png">
JavaScript
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/?[A-z]*;base64,/);
}
var base64 = getBase64Image(document.getElementById("imageid"));
Special thanks to @Md. Hasan Mahmud for providing an improved regex that works with any image mime type in my comments!
This method requires the canvas element, which is perfectly supported.
- The MDN reference of
HTMLCanvasElement.toDataURL(). - And the official W3C documentation.
View this answer: https://stackoverflow.com/a/20285053/5065874 by @HaNdTriX
Basically, he implemented this function:
function toDataUrl(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
And in your case, you can use it like this:
toDataUrl(imagepath, function(myBase64) {
console.log(myBase64); // myBase64 is the base64 string
});
» npm install image-to-base64
This worked for me:
TS FILE
base64ImageString;
async getBase64ImageFromUrl(imageUrl) {
var res = await fetch(imageUrl);
var blob = await res.blob();
return new Promise((resolve, reject) => {
var reader = new FileReader();
reader.addEventListener("load", function () {
resolve(reader.result);
}, false);
reader.onerror = () => {
return reject(this);
};
reader.readAsDataURL(blob);
})
}
ngOnInit() {
this.getBase64ImageFromUrl(this.userData.organization_logo).then(base64 => {
this.base64ImageString = base64;
})
}
HTML
<img src='{{ base64ImageString }}' class="logo" />
you can do like this, and maybe you need to resolve the origin cross if the img url is not the same origin
const image = new Image();
image.onload = function(){
const width = image.width;
const height = image.height;
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx.drawImage(image, 0, 0);
const base64 = canvas.toDataURL({format: "png"})
console.log(base64);
}
image.src = 'https://cdn.pixabay.com/photo/2015/02/24/15/41/dog-647528__340.jpg';
HTML
<img id="imageid" src="https://www.google.de/images/srpr/logo11w.png">
JavaScript
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/?[A-z]*;base64,/);
}
var base64 = getBase64Image(document.getElementById("imageid"));
Special thanks to @Md. Hasan Mahmud for providing an improved regex that works with any image mime type in my comments!
This method requires the canvas element, which is perfectly supported.
- The MDN reference of
HTMLCanvasElement.toDataURL(). - And the official W3C documentation.
View this answer: https://stackoverflow.com/a/20285053/5065874 by @HaNdTriX
Basically, he implemented this function:
function toDataUrl(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
And in your case, you can use it like this:
toDataUrl(imagepath, function(myBase64) {
console.log(myBase64); // myBase64 is the base64 string
});
You can use this to get base64 image
async function getBase64ImageFromUrl(imageUrl) {
var res = await fetch(imageUrl);
var blob = await res.blob();
return new Promise((resolve, reject) => {
var reader = new FileReader();
reader.addEventListener("load", function () {
resolve(reader.result);
}, false);
reader.onerror = () => {
return reject(this);
};
reader.readAsDataURL(blob);
})
}
Then call it like this
getBase64ImageFromUrl('your url')
.then(result => testImage.src = result)
.catch(err => console.error(err));
works like charm in pdfMake and angular
You can use this function to create generate a base64 image
toDataURL = async (url) => {
console.log("Downloading image...");
var res = await fetch(url);
var blob = await res.blob();
const result = await new Promise((resolve, reject) => {
var reader = new FileReader();
reader.addEventListener("load", function () {
resolve(reader.result);
}, false);
reader.onerror = () => {
return reject(this);
};
reader.readAsDataURL(blob);
})
return result
};
and then call it like this
imageSrcString = await this.toDataURL(imageSrc)
You can do the following...
First, convert the data URL to a blob:
convertDataUrlToBlob(dataUrl): Blob {
const arr = dataUrl.split(',');
const mime = arr[0].match(/:(.*?);/)[1];
const bstr = atob(arr[1]);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {type: mime});
}
Next, use the blob to create an object URL:
const objectURL = URL.createObjectURL(convertDataUrlToBlob(dataUrl));
Finally, use the object URL as the src of your image:
document.getElementById('myImage').src = objectURL;
If you want, you can also convert the Blob into a File:
const file = new File([convertDataUrlToBlob(dataUrl)], filename, {type: `image/${extension}`});
<image-cropper [imageURL]="fileurl">
</image-cropper>
imageURL will accept any variable like "fileurl" in .ts file