Quote from
asmat on August 3, 2024, 9:18 pm
Hi everyone,
I’m working on a project using VisualNEO Web, and I need to convert one of my subroutines into an asynchronous function. Could someone guide me on how to accomplish this?
async function imageUrlToBase64(url) {
try {
// Fetch the image data
const response = await fetch(url);
// Ensure the response is successful
if (!response.ok) {
throw new Error('Network response was not ok');
}
// Get the image data as a Blob
const blob = await response.blob();
// Create a FileReader to read the Blob
const reader = new FileReader();
// Return a promise that resolves with the Base64 data
return new Promise((resolve, reject) => {
reader.onloadend = () => {
// The Base64 string is stored in reader.result
resolve(reader.result);
};
reader.onerror = () => {
reject(new Error('Failed to read the Blob'));
};
// Read the Blob as a Data URL (Base64)
reader.readAsDataURL(blob);
});
} catch (error) {
console.error('Error converting image URL to Base64:', error);
throw error;
}
}
// Example usage
const url = "https://firebasestorage.googleapis.com/v0/b/kankor-plus-80e20.appspot.com/o/profiles%2F004RAGNHQUb6FZNZjsC06FNgSdf1.PNG?alt=media&token=14d75003-c8e3-47b9-8313-893434c835a3";
imageUrlToBase64(url)
.then(base64String => {
console.log('Base64 String:', base64String);
})
.catch(error => {
console.error('Error:', error);
});
Hi everyone,
I’m working on a project using VisualNEO Web, and I need to convert one of my subroutines into an asynchronous function. Could someone guide me on how to accomplish this?
async function imageUrlToBase64(url) {
try {
// Fetch the image data
const response = await fetch(url);
// Ensure the response is successful
if (!response.ok) {
throw new Error('Network response was not ok');
}
// Get the image data as a Blob
const blob = await response.blob();
// Create a FileReader to read the Blob
const reader = new FileReader();
// Return a promise that resolves with the Base64 data
return new Promise((resolve, reject) => {
reader.onloadend = () => {
// The Base64 string is stored in reader.result
resolve(reader.result);
};
reader.onerror = () => {
reject(new Error('Failed to read the Blob'));
};
// Read the Blob as a Data URL (Base64)
reader.readAsDataURL(blob);
});
} catch (error) {
console.error('Error converting image URL to Base64:', error);
throw error;
}
}
// Example usage
const url = "https://firebasestorage.googleapis.com/v0/b/kankor-plus-80e20.appspot.com/o/profiles%2F004RAGNHQUb6FZNZjsC06FNgSdf1.PNG?alt=media&token=14d75003-c8e3-47b9-8313-893434c835a3";
imageUrlToBase64(url)
.then(base64String => {
console.log('Base64 String:', base64String);
})
.catch(error => {
console.error('Error:', error);
});