How to generate video thumbnail from input file in javascript? - javascript

How to draw an image thumbnail of a video from input file? This is what i've tried so far
let targetInput = document.getElementById('video-input');
targetInput.addEventListener('change', function(e) {
let videoMetaData = (file) => {
return new Promise(function(resolve, reject) {
let video = document.createElement('video');
// video.preload = 'metadata';
video.onloadedmetadata = function() {
// window.URL.revokeObjectURL(video.src);
// console.log(video.src)
resolve({
video: video,
duration: Math.round(video.duration * 1000),
height: video.videoHeight,
width: video.videoWidth
})
}
video.src = URL.createObjectURL(file);
})
}
videoMetaData(e.target.files[0]).then(function(value) {
let videoCanvas = document.createElement('canvas');
videoCanvas.height = value.height;
videoCanvas.width = value.width;
videoCanvas.getContext('2d').drawImage(value.video, 0, 0)
var snapshot = videoCanvas.toDataURL();
console.log(snapshot)
})
})
<input type="file" id="video-input" />
This code is working. You can see the result on your browser console, but why the image URI result was blank?

I can only think of this: You are missing to append the <video> element to the body after creating: document.createElement('video');
You just need to append it for testing:
// after this line
video.src = URL.createObjectURL(file);
// try this...
video.controls = 'controls';
document.body.appendChild(video);
Update:
let targetInput = document.getElementById('video-input');
targetInput.addEventListener('change', function(e) {
let videoMetaData = (file) => {
return new Promise(function(resolve, reject) {
let video = document.createElement('video');
// video.preload = 'metadata';
video.addEventListener('canplay', function () {
resolve({
video: video,
duration: Math.round(video.duration * 1000),
height: video.videoHeight,
width: video.videoWidth
});
});
video.src = URL.createObjectURL(file);
document.body.appendChild(video);
video.play();
})
}
videoMetaData(this.files[0]).then(function(value) {
let videoCanvas = document.createElement('canvas');
videoCanvas.height = value.height;
videoCanvas.width = value.width;
videoCanvas.getContext('2d').drawImage(value.video, 0, 0);
var snapshot = videoCanvas.toDataURL('image/png');
var img = new Image();
img.onload = function () {
document.body.appendChild(this);
};
img.src = snapshot;
})
})
<input type="file" id="video-input" />

Related

Face-api.js for detecting face expression not working on IOS

I am using face-api.js for detecting face expression.On IOS devices(Ipad, Iphone) camera is not getting opened but in android it is working fine.
Code That i am using
Can anyone help me why it is not getting opened on IOS please.
`
async ngOnInit() {
await Promise.all([faceapi.nets.tinyFaceDetector.loadFromUri('../../../assets/models'),
await faceapi.nets.faceLandmark68Net.loadFromUri('../../../assets/models'),
await faceapi.nets.faceRecognitionNet.loadFromUri('../../../assets/models'),
await faceapi.nets.faceExpressionNet.loadFromUri('../../../assets/models'),]).then(() => this.startVideo());
}
startVideo() {
this.videoInput = this.video.nativeElement;
navigator.getUserMedia(
{ video: {}, audio: false },
(stream:any) =>{ this.videoInput.srcObject = stream},
(err:any) =>{ console.log(err)}
);
this.detect_Faces();
}
async detect_Faces() {
this.elRef.nativeElement.querySelector('video').addEventListener('play', async () => {
this.show_tip = true;
this.canvas = await faceapi.createCanvasFromMedia(this.videoInput);
this.canvasEl = this.canvasRef.nativeElement;
this.canvasEl.appendChild(this.canvas);
this.canvas.setAttribute('id', 'canvass');
this.canvas.setAttribute(
'style',`position: fixed;
top: 0;
left: 0;
autoplay: true;
controls: true;
playsinline: true;
loop: true;`
);
this.displaySize = {
width: this.videoInput.width,
height: this.videoInput.height,
};
faceapi.matchDimensions(this.canvas, this.displaySize);
// setInterval(async () => {
this.detection = await faceapi.detectAllFaces(this.videoInput, new faceapi.TinyFaceDetectorOptions()).withFaceLandmarks().withFaceExpressions();
this.resizedDetections = faceapi.resizeResults(
this.detection,
this.displaySize
);
this.canvas.getContext('2d').clearRect(0, 0, this.canvas.width,this.canvas.height);
if (this.resizedDetections.length > 0 ) {
const canvas = document.createElement('canvas');
canvas.width = 1600;
canvas.height = 1200;
canvas.getContext('2d').drawImage(this.video.nativeElement, 0, 0);
const img = document.createElement("img");
// const dataUrl =
// img.src = canvas.toDataURL("image/png");
// img.src = URL.createObjectURL(p);
img.src = canvas.toDataURL().replace("image/base64", "image/webp");
// document.getElementById('screenshot').appendChild(img)
console.log(img.src);
this.faceSearch(img.src);
}
});
}
`
the same code is working on Android but not on IOS

Oracle Apex - BLOB to jpg

I'm trying to pass a jpg that I have stored in a table as a blob to the following javascript code:
class ImageLoader {
constructor(imageWidth, imageHeight) {
this.canvas = document.createElement('canvas');
this.canvas.width = imageWidth;
this.canvas.height = imageHeight;
this.ctx = this.canvas.getContext('2d');
}
async getImageData(url) {
await this.loadImageAsync(url);
const imageData = this.ctx.getImageData(0, 0, this.canvas.width, this.canvas.height);
return imageData;
}
loadImageAsync(url) {
return new Promise((resolve, reject) => {
this.loadImageCb(url, () => {
resolve();
});
});
}
loadImageCb(url, cb) {
loadImage(
url,
img => {
if (img.type === 'error') {
throw `Could not load image: ${url}`;
} else {
// load image data onto input canvas
this.ctx.drawImage(img, 0, 0)
//console.log(`image was loaded`);
window.setTimeout(() => { cb(); }, 0);
}
},
{
maxWidth: this.canvas.width,
maxHeight: this.canvas.height,
cover: true,
crop: true,
canvas: true,
crossOrigin: 'Anonymous'
}
);
}
}
I've tried get APEX_UTIL.GET_BLOB_FILE_SRC, but then the javascript code throws the error "Could not load image".
I then to use the following procedure:
create or replace PROCEDURE get_file (p_file_name IN VARCHAR2) IS
l_blob_content UPLOADED_IMAGES.blob_content%TYPE;
l_mime_type UPLOADED_IMAGES.mime_type%TYPE;
BEGIN
SELECT blob_content,
mime_type
INTO l_blob_content,
l_mime_type
FROM UPLOADED_IMAGES
WHERE filename = p_file_name;
sys.HTP.init;
sys.OWA_UTIL.mime_header(l_mime_type, FALSE);
sys.HTP.p('Content-Length: ' || DBMS_LOB.getlength(l_blob_content));
sys.HTP.p('Content-Disposition: filename="' || p_file_name || '"');
sys.OWA_UTIL.http_header_close;
sys.WPG_DOCLOAD.download_file(l_blob_content);
apex_application.stop_apex_engine;
EXCEPTION
WHEN apex_application.e_stop_apex_engine
THEN RAISE;
WHEN OTHERS THEN
HTP.p('Whoops');
END;
Still the same error "Could not load image" and a new error "Whoops Status:204 No Content X-Content-Type-Options:nosniff X-Xss-Protection:1; mode=block Referrer-Policy:strict-origin Cache-Control:no-store Pragma:no-cache Expires:Sun, 27 Jul 1997 13:00:00 GMT X-Frame-Options:SAMEORIGIN".
So I'm not sure what I'm doing wrong or how to better go about doing this right.
Update:
I've now tried "blob2clobbase64", but that doesn't seem to anything:
declare
l_image_clob clob;
l_image_blob blob;
begin
select BLOB_CONTENT
into l_image_blob
from UPLOADED_IMAGES
where FILENAME = :P1_IMAGES;
l_image_clob := apex_web_service.blob2clobbase64(
p_blob => l_image_blob
);
apex_json.open_object;
apex_json.write('imageBase64', l_image_clob );
apex_json.close_object;
end;
The code I'm using for image loading:
const imageSize = 224;
const imageBLOB = new Image();
// Load image.
apex.server.process(
"get_file",
{},
{
success: function(data) {
imageBLOB.src = 'data:image/jpeg;base64,' + data.imageBase64;
const imageLoader = new ImageLoader(imageSize, imageSize);
const imageData = await imageLoader.getImageData(imageBLOB);
}
}
);
I got it to work. I ended up using the "blob2clobbase64" process and instead of using the ImageLoader class and instead used getImageData from the canvas. The PL/SQL is the same but the JavaScript is different:
const imageSize = 224;
var newImageDate;
function returnImageData(imageData){
return newImageDate = imageData;
}
async function runImageExample(){
apex.server.process(
"get_image", {}, {
success: async function(data) {
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var imageBLOB = new Image();
imageBLOB.onload = function() {
imageBLOB.crossOrigin = "Anonymous";
ctx.drawImage(imageBLOB, 0, 0, imageSize, imageSize);
var imgData = ctx.getImageData(0, 0, imageSize, imageSize);
returnImageData(imgData.data);
};
imageBLOB.src = 'data:image/jpeg;base64,' + data.photoBase64;
}
}
);
}

Convert Image uri into Base64 [duplicate]

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 = $("#imageid").val();// from this getting the path of the selected image
that var st = imagepath.replace(data:image/png or jpg; base64"/"");
How to convert the image 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
});
In todays JavaScript, this will work as well..
const getBase64FromUrl = async (url) => {
const data = await fetch(url);
const blob = await data.blob();
return new Promise((resolve) => {
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = () => {
const base64data = reader.result;
resolve(base64data);
}
});
}
getBase64FromUrl('https://lh3.googleusercontent.com/i7cTyGnCwLIJhT1t2YpLW-zHt8ZKalgQiqfrYnZQl975-ygD_0mOXaYZMzekfKW_ydHRutDbNzeqpWoLkFR4Yx2Z2bgNj2XskKJrfw8').then(console.log)
This is your html-
<img id="imageid" src="">
<canvas id="imgCanvas" />
Javascript should be-
var can = document.getElementById("imgCanvas");
var img = document.getElementById("imageid");
var ctx = can.getContext("2d");
ctx.drawImage(img, 10, 10);
var encodedBase = can.toDataURL();
'encodedBase' Contains Base64 Encoding of Image.
You Can Used This :
function ViewImage(){
function getBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}
var file = document.querySelector('input[type="file"]').files[0];
getBase64(file).then(data =>$("#ImageBase46").val(data));
}
Add To Your Input onchange=ViewImage();
I try using the top answer, but it occur Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
I found this is because of cross domain problems, the solution is
function convert(oldImag, callback) {
var img = new Image();
img.onload = function(){
callback(img)
}
img.setAttribute('crossorigin', 'anonymous');
img.src = oldImag.src;
}
function getBase64Image(img,callback) {
convert(img, function(newImg){
var canvas = document.createElement("canvas");
canvas.width = newImg.width;
canvas.height = newImg.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(newImg, 0, 0);
var base64=canvas.toDataURL("image/png");
callback(base64)
})
}
getBase64Image(document.getElementById("imageid"),function(base64){
// base64 in here.
console.log(base64)
});
<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL();" />
<div id="imgTest"></div>
<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>
let baseImage = new Image;
baseImage.setAttribute('crossOrigin', 'anonymous');
baseImage.src = your image url
var canvas = document.createElement("canvas");
canvas.width = baseImage.width;
canvas.height = baseImage.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(baseImage, 0, 0);
var dataURL = canvas.toDataURL("image/png");
Additional information about "CORS enabled images": MDN Documentation
imageToBase64 = (URL) => {
let image;
image = new Image();
image.crossOrigin = 'Anonymous';
image.addEventListener('load', function() {
let canvas = document.createElement('canvas');
let context = canvas.getContext('2d');
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, 0, 0);
try {
localStorage.setItem('saved-image-example', canvas.toDataURL('image/png'));
} catch (err) {
console.error(err)
}
});
image.src = URL;
};
imageToBase64('image URL')
Here's the Typescript version of Abubakar Ahmad's answer
function imageTo64(
url: string,
callback: (path64: string | ArrayBuffer) => void
): void {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
xhr.onload = (): void => {
const reader = new FileReader();
reader.readAsDataURL(xhr.response);
reader.onloadend = (): void => callback(reader.result);
}
}
Just wanted to chime in and post how I did it. This is basically #Haialaluf's approach but a bit shorter:
const imageUrlToBase64 = async (url) => {
const data = await fetch(url)
const blob = await data.blob();
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = () => {
const base64data = reader.result;
return base64data
}
}

trying to record a video with javascript using a webcam without a service

i am trying to create a web page that displays the camera at start-up when press a button starts recording and press button to stop recording the play the video after it stops recording. i have it showing the camera but the button functions are currently not working. i will show u my code
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8">
<title>Display Webcam Stream</title>
<link rel="stylesheet" type="text/css" href="css.css"/>
</head>
<body>
<button id="btn-start-recording" onclick="go()">Start Recording now</button>
<button id="btn-stop-recording" onclick="stop()">stop recording</button>
<div id="container">
<video autoplay="true" id="videoElement"></video>
<canvas id="myCanvas" width="500" height="375"></canvas>
</div>
<script src="recording.js"></script>
</body>
</html>
My javascript:
var video = document.querySelector("#videoElement");
if (navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({ video: true, audio: true })
.then(function (stream) {
video.srcObject = stream;
})
.catch(function (err0r) {
console.log("Something went wrong!");
alert("you need a webcam and micophone to record a Video");
document.getElementById("btn-start-recording").disabled = true;
//document.getElementById("btn-stop-recording").disabled = true;
});
}
var newvideo = document.getElementById("video");
//startup();
function stop() {
var stream = video.srcObject;
var tracks = stream.getTracks();
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i];
track.stop();
}
stopRecording();
alert("started");
// var create = "false";
// recording(create);
}
function stopRecording() {
var chunks = [];
// var blob = new Blob(chunks, { 'type' : 'video/mp4' });
let blob = recorder.getBlob();
var videoURL = URL.createObjectURL(blob);
if(videoURL != null) {
video.src = videoURL;
video.play();
}
else
alert("Error didn't create video please try again");
}
function gorecording() {
navigator.mediaDevices.getUserMedia({
video: true,
audio: true
}).then(async function(stream) {
let recorder = RecordRTC(stream, {
type: 'video'
});
recorder.startRecording();
const sleep = m => new Promise(r => setTimeout(r, m));
await sleep(3000);
recorder.stopRecording(function() {
let blob = recorder.getBlob();
invokeSaveAsDialog(blob);
});
});
}
function draw () {
ctx.fillStyle = colors[Math.floor(Math.random() * colors.length)];
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
function startRecording() {
var canvas = document.getElementById("canvas");
var video = document.getElementById("videoElement");
var colors = ["red", "blue", "yellow", "orange", "black", "white", "green"];
draw();
//var ctx = canvas.getContext("2d");
alert("helloooo");
}
function SstartRecording() {
var ctx = canvas.getContext("2d");
alert("helloooo");
var video = document.querySelector("video");
var colors = ["red", "blue", "yellow", "orange", "black", "white", "green"];
draw();
var videoStream = canvas.captureStream(30);
var mediaRecorder = new MediaRecorder(videoStream);
var chunks = [];
mediaRecorder.ondataavailable = function(e) {
chunks.push(e.data);
};
mediaRecorder.onstop = function(e) {
var blob = new Blob(chunks, { 'type' : 'video/mp4' });
chunks = [];
var videoURL = URL.createObjectURL(blob);
video.src = videoURL;
};
mediaRecorder.ondataavailable = function(e) {
chunks.push(e.data);
};
mediaRecorder.start();
setInterval(draw, 300);
setTimeout(function (){ mediaRecorder.stop(); }, 5000);
alert("hello");
}
//}
function go() {
//var create = "true";
startRecording();
//recording(create);
}
function recording(create) {
var canvas = document.querySelector("#myCanvas");
var videoStream = canvas.captureStream(30);
var mediaRecorder = new MediaRecorder(videoStream);
var chunks = [];
mediaRecorder.ondataavailable = function(e) {
chunks.push(e.data);
};
mediaRecorder.onstop = function(e) {
var blob = new Blob(chunks, { 'type' : 'video/mp4' });
chunks = [];
var videoURL = URL.createObjectURL(blob);
video.src = videoURL;
};
if (create == "true") {
mediaRecorder.start();
} else {
mediaRecorder.stop();
}
}
And my css :
.display-cover {'
display: flex;
justify-content: center;
align-items: center;
width: 70%;
margin: 5% auto;
position: relative;
}
/*
#container
{
position: absolute;
left: 20px;
top: 30px;
} */
#videoElement {
width: 100%;
background: rgba(0, 0, 0, 0.2);
}
body{
background-color: aqua;
}
does anyone have any ideas?

Convert image from url to Base64

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 = $("#imageid").val();// from this getting the path of the selected image
that var st = imagepath.replace(data:image/png or jpg; base64"/"");
How to convert the image 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
});
In todays JavaScript, this will work as well..
const getBase64FromUrl = async (url) => {
const data = await fetch(url);
const blob = await data.blob();
return new Promise((resolve) => {
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = () => {
const base64data = reader.result;
resolve(base64data);
}
});
}
getBase64FromUrl('https://lh3.googleusercontent.com/i7cTyGnCwLIJhT1t2YpLW-zHt8ZKalgQiqfrYnZQl975-ygD_0mOXaYZMzekfKW_ydHRutDbNzeqpWoLkFR4Yx2Z2bgNj2XskKJrfw8').then(console.log)
This is your html-
<img id="imageid" src="">
<canvas id="imgCanvas" />
Javascript should be-
var can = document.getElementById("imgCanvas");
var img = document.getElementById("imageid");
var ctx = can.getContext("2d");
ctx.drawImage(img, 10, 10);
var encodedBase = can.toDataURL();
'encodedBase' Contains Base64 Encoding of Image.
You Can Used This :
function ViewImage(){
function getBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}
var file = document.querySelector('input[type="file"]').files[0];
getBase64(file).then(data =>$("#ImageBase46").val(data));
}
Add To Your Input onchange=ViewImage();
I try using the top answer, but it occur Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
I found this is because of cross domain problems, the solution is
function convert(oldImag, callback) {
var img = new Image();
img.onload = function(){
callback(img)
}
img.setAttribute('crossorigin', 'anonymous');
img.src = oldImag.src;
}
function getBase64Image(img,callback) {
convert(img, function(newImg){
var canvas = document.createElement("canvas");
canvas.width = newImg.width;
canvas.height = newImg.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(newImg, 0, 0);
var base64=canvas.toDataURL("image/png");
callback(base64)
})
}
getBase64Image(document.getElementById("imageid"),function(base64){
// base64 in here.
console.log(base64)
});
<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL();" />
<div id="imgTest"></div>
<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>
let baseImage = new Image;
baseImage.setAttribute('crossOrigin', 'anonymous');
baseImage.src = your image url
var canvas = document.createElement("canvas");
canvas.width = baseImage.width;
canvas.height = baseImage.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(baseImage, 0, 0);
var dataURL = canvas.toDataURL("image/png");
Additional information about "CORS enabled images": MDN Documentation
imageToBase64 = (URL) => {
let image;
image = new Image();
image.crossOrigin = 'Anonymous';
image.addEventListener('load', function() {
let canvas = document.createElement('canvas');
let context = canvas.getContext('2d');
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, 0, 0);
try {
localStorage.setItem('saved-image-example', canvas.toDataURL('image/png'));
} catch (err) {
console.error(err)
}
});
image.src = URL;
};
imageToBase64('image URL')
Here's the Typescript version of Abubakar Ahmad's answer
function imageTo64(
url: string,
callback: (path64: string | ArrayBuffer) => void
): void {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
xhr.onload = (): void => {
const reader = new FileReader();
reader.readAsDataURL(xhr.response);
reader.onloadend = (): void => callback(reader.result);
}
}
Just wanted to chime in and post how I did it. This is basically #Haialaluf's approach but a bit shorter:
const imageUrlToBase64 = async (url) => {
const data = await fetch(url)
const blob = await data.blob();
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = () => {
const base64data = reader.result;
return base64data
}
}

Categories