We have a corporate React Typescript project, in one part of which we scrape images from websites, encode to base64, write to the database and then display to the end-user.
Here is very simplified example of our code, just App.tsx
:
const App = (): JSX.Element => {
const jpgbase64 = "/9j/4AAQSkZJRgABAQAAAQABAA .... nveHWYNjqKqrk5I7zc/wAvhOHaHTwM/wDeA/7BPVLtD+OAIPmZfad";
const pngbase64 = "iVBORw0KGgoAAAANSU .... lCgQUKJAQIkCASUKBJQoEFCiQECJAgElCgSUKBBQokBAiQIBJQoElCgQUKJAQIkCASUKBJQoEFCiQECJAgElCgSUKBBQokBAiQIBJQoElCgQUKJAQIkCASUKBJQoEFCiQECJAgElCgSUKBBQokBAiQIBJQoElCgQUKJAQIkCASUKBJQoEFCiQECJAgElCgSUKBBQokBAiQIBJQoElCgQUKJAQIkCAaX/AcrFIKL9KpbnAAAAAElFTkSuQmCC";
return (
<>
<span className="fakeHtml">{"<div> with base64 JPEG and PNG <img>s:"}</span>
<div className="imgHolder">
<img src={"data:image/jpeg;base64, " + jpgbase64} />
<img src={"data:image/png;base64, " + pngbase64} />
</div>
</>
);
};
export default App;
Both jpgbase64
and pngbase64
are valid base64 strings.
A weird things are: when we open this simple example page in Firefox, initially both images were loaded:
But then if we refresh a page by selecting site address in address bar and then hitting Enter, JPEG image disappears, but PNG is still here!
Then hitting F5 is not returning image back:
Please feel free to check this short video of how to reproduce.
Question: how to make JPEG image not to disappear after page refresh?
At the same time, <div className="imgHolder">
is existing in DOM with both images inside; no errors/warnings in the console. Everything except a problem I mentioned seems to be fine.
When we open that simple example page in Chrome, both images loading correctly, even when we refresh a page multiple times.
If just save a page from browser by hitting Ctrl + S, and then open from saved file, everything seems to work fine as well.
Have a look at your developer console. There is an error which states that the image is truncated. It cannot be cached correctly by Firefox. Apparently other browsers can but with larger files would probably fail too.
Base64 is a string filled with groups of four 6-bit characters (A-Z, a-z, 0-9). An image in Base64 is always at least a third larger than a binary image file. Your users’ CPUs need to do extra work to decode the image.
Would your application be able to work with blobs instead? If so, then you would be able to use createObjectURL