'How to display a png image encoded in base64 format in react
I am working on a project that takes an image from an API and inserts it into an tag. The API returns the image in a png format and I am taking it and turning it into base 64 format.
When the contents of the image are printed it looks like this: <Buffer 22 ef bf bd 50 4e 47 5c 72 5c 6e 5c 75 30 30 31 61 5c 6e 5c 75 30 30 30 30 5c 75 30 30 30 30 5c 75 30 30 30 30 5c 72 49 48 44 52 5c 75 30 30 30 30 5c ... 3996 more bytes>
Here is my backend code for getting the image. I have a list of countries in a separate file and am inserting it into the URL to get a random country's flag.
app.get("/countryflags", async (req, res) => {
let country = countries[Math.floor(Math.random() * countries.length)];
console.log(country);
try {
console.log(country)
const response = await axios.get(`https://countryflagsapi.com/png/${country}`, {
responseType: "arrayBuffer"
});
let base64ImageString = Buffer.from(JSON.stringify(response.data).toString("base64"));
console.log(base64ImageString)
if(response.status === 200){
console.log("Image sent back")
res.status(200).json({image: base64ImageString});
}
} catch(err) {
console.log(err);
res.status(500).json({message: "Error"});
}
});
Here is the frontend code:
const [image, setImage] = useState("");
const generateCountryImage = async () => {
const res = await axios.get("https://sudokuguessrbackend.yxli666.repl.co/countryflags");
const country = res.data.image;
setImage(country);
// Get the corresponding image
}
Which I then set in a react component:
<img src = {`data:image/png;base64,${image}`}/>
Instead of running though, the image is not displayed. In a similar way to if alt text was needed. Not sure what to do. Any help would be greatly appreciated!
Solution 1:[1]
You can actually do it with html5 canvas and you can resize it to the size of your image:
var myImage = new Image();
myImage.src = imgData;
ctx.drawImage(myImage, 0, 0);
You can learn more about this here
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ca1c |
