My JavaScript script is dealing with a string containing an encoded image.jpeg that was created using OpenCV in C++:
cv::imencode(".jpeg", rgb_img, jpeg_data);
std::string jpeg_string(jpeg_data.begin(), jpeg_data.end());
The next step involves passing this string through a websocket. In my JS code, I need to decode the string and use it as the src attribute for an img tag. I attempted two methods, one from ChatGPT and another from Stack Overflow:
// Approach 1
var arrayBuffer = new ArrayBuffer(jpeg_string.length);
var uint8Array = new Uint8Array(arrayBuffer);
for (var i = 0; i < jpeg_string.length; i++) {
uint8Array[i] = jpeg_string.charCodeAt(i);
}
var blob = new Blob([arrayBuffer], { type: 'image/jpeg' });
var imageDataUri = URL.createObjectURL(blob);
img.src = imageDataUri;
// Approach 2
const imageDataUri = `data:image/jpeg;base64,${jpeg_string}`;
img.src = imageDataUri;
However, both approaches are not yielding the desired result. The first method results in a src value like
blob:http://0.0.0.0:7000/<random numbers, lowercase letters and dashes>
, and the second method produces data:image/jpeg;base64,<uppercase letters and numbers>
. How can I successfully display the image?I am using Robot Operating System on Ubuntu 22.4 (though this information should not affect the solution).