I am curious as to what browsers (Specifically chrome) are doing when you set an img tags src to a path which returns a png binary string vs. if you would call this endpoint manually (Say using Ajax or Axios) and then set the images src to this PNG binary manually. Because the results are different between the two.
I am running a Node/expressJs server, which has an image file which returns from the images/
path.
router.get('images/', async function(req, res) {
try {
return await fs
.createReadStream('./images/sample.png')
.pipe(res);
} catch (err) {
res.status(400).json({ message: err.message });
}
});
This API call will return a PNG binary string.
If I will set the img element as such <img src="http://localhost/images/"
This call will return the PNG binary from my Node server and automatically display everything correctly.
If however, I would use a library like axios, to call this endpoint manually, I would get back a PNG binary string (In the chrome dev-tools 'network' tab, when looking at repsonse data, I even see a nice preview thumbnail of the image, so something in that panel is also correctly taking the PNG data and displaying it in an img element there). But if I will take this data and try to set it to the src of the image tag, I need to do all kinds of base64 conversions before it will work.
So my question is - What is the internal algo of the img element, for when it receives binary image data from a server?
There is no 'internal algorithm'. src
is an HTML attribute that expects a URI, whether it is an HTTP URI or a Base64 URI. The reason you have to convert the data to Base64 if you request the image using JavaScript is because this is the most straightforward way to represent binary data as a URI. When the browser sees a Base64 URI, then it just converts it back into binary data and displays it.