In my React project, I first pull the full image from database as Base64 encoded string, and then display it in a webpage, like the following:
...react code...
return {
<img src='data:image/jpeg;base64, /9j/4A.../>
}
I want to create a simply function that can take base64 encoded image as input, and output a new base64 encoded image with smaller size as the thumbnail, something like:
...react code...
return {
<img src={createThumbnail('data:image/jpeg;base64, /9j/4A...)}/>
}
I found examples such as Creating thumbnail from existing base64 image, and base on which I tried something like below but the image will not get a src at all because the reason stated in the 1st post.
const createThumbnail = (base64Image, callback = x => {return x;}) => {
console.log(base64Image)
const img = new Image();
img.src = base64Image;
img.onload = () => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, 100, 100);
const thumbnail = canvas.toDataURL('image/jpeg');
console.log(thumbnail)
callback(thumbnail);
}
}
I do not understand why I need to use canvas or img.onload(...)
, since I have the base64 string already, how can I just open it as an image, shrink its size, and return the new image as base64?