I'm (relatively) new to software dev and am stuck with trying to display a Base64 Binary image in a React component.
Problem: I'm ultimately trying to display a Buffer JPEG Image in an<img />
tag with a React component.
Using screenshot-desktop npm package (https://www.npmjs.com/package/screenshot-desktop) to capture desktop.
screenshot() returns a Promise which exposes a Buffer JPEG object.
Based on numerous posts, I have tried to convert this to a Base64 format and then update state so that I can subsequently access the Base64 image to include as a src in the image tag.
Here are the key parts of my code:-
const screenshot = require("screenshot-desktop");
function ScreenCapturer(props) {
const [image, setImage] = useState("");
function captureCurrentScreen() {
screenshot().then((bufferedImage) => {
let base64Image = btoa(bufferedImage);
setImage(base64Image);
});
}
return (
<div >
<img className="image-holder" alt="" src={`data:image/jpeg;base64,${image}`}/>
<h3>Image Capturer</h3>
<h4>Base64Image : {image.substring(1, 20)}</h4>
<button
onClick={() => {
captureCurrentScreen();
}}
>
Capture
</button>
</div>
);
}
Key Issues:-
With the above code, I realise that the initial
src
value won't display anything.On clicking the button, I'm able to display the first 20 characters of the Base64 image, so I believe that the conversion process is working. After pressing the button, no image is shown nor is there any error shown.
Note: On checking devTools in the chrome Bowser, the object that screenshot() produces is stated as "Uint8 array"
Question: My understanding is that the component should re-render on setting a new state. Where am I going wrong ? Any help would be much appreciated.