I'm gonna save the online image as base64 to localstorage.
So I referenced the following code.
<script>
function getBase64Image() {
var img = new Image();
img.crossOrigin = "anonymous"; // Set the CORS attribute
// Use a CORS proxy to fetch the image
var imageUrl = "https://example.com/path/to/your/image.jpg";
var proxyUrl = "https://cors-anywhere.herokuapp.com/";
img.src = proxyUrl + imageUrl;
// Ensure the image is fully loaded
img.onload = function() {
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/jpeg'); // You can also use 'image/png'
var base64String = dataURL.replace(/^data:image\/(png|jpeg);base64,/, '');
localstorage.setItem("data", base64String);
};
// Handle the image loading error
img.onerror = function() {
console.error('Image failed to load. Please check the URL and CORS policy.');
};
}
</script>
But encountered the CORS error.
The image source is an online URL and does not support CORS.
How to fix this issue and get the base64 string from online image using Javascript or Node JS
If handling the image on the client side continues to be problematic, consider processing the image on the server side. This way, you can bypass CORS issues entirely. Here’s a basic example using Node.js and Express:
app.get('/fetch-image', async (req, res) => {
const imageUrl = 'https://example.com/path/to/your/image.jpg';
try {
const response = await axios.get(imageUrl, { responseType: 'arraybuffer' });
const base64Image = Buffer.from(response.data, 'binary').toString('base64');
res.send(base64Image);
} catch (error) {
res.status(500).send('Failed to fetch image');
}
});