Having trouble converting Buffered Byte Array into Image in Browser

Hello there! I am currently facing an issue while attempting to generate an image from a buffered byte array. The reason behind this is that I need to transfer the image from the server to the client using JSON. Below is the code snippet in question:

The index.html file represents the client side.

<img id="ItemPreview">

<script>
    var socket = new WebSocket("ws://localhost:8080");
    socket.onopen = function(event){
        setTimeout(function(){
            var message = JSON.stringify({"task" : "initialize", "data" : ""});
            socket.send(message);
        }, 1000);
    };
    socket.onmessage = function(event){
        var json = JSON.parse(event.data);
        if(json.task == "display-image"){
            console.log("From Client\t\t: " + json);
            console.log(json.data.data);
            var urlCreator = window.URL || window.webkitURL;
            //var imageUrl = urlCreator.createObjectURL(json.data);
            var imageUrl = urlCreator.createObjectURL(new Blob(json.data.data));
            document.querySelector("#ItemPreview").src = imageUrl;
            //document.querySelector("#ItemPreview").src = "data:image/png;base64," + json.data.data;
            var message = JSON.stringify({  "task" : "get-image", "data" : ""});
            socket.send(message);
        }
    };

</script>

I have also attempted what was mentioned in the comments, but unfortunately, I haven't been successful...

On the other hand, the server side is represented by the index.js file.

//index.js

var server = require('ws').Server;
var s = new server({ port : 8080 });
var fs = require('fs');

s.on('connection', function(ws){

    ws.on('message', function(message){
        var json = JSON.parse(message);
        console.log("From Server:\t\t" + json);
        if(json.task == "initialize"){
            var image = fs.readFileSync("./img/1.jpg");
            var messageToSend = JSON.stringify({
                "task" : "display-image",
                "data" : image
            });
            ws.send(messageToSend);
        }
    });

    ws.on('close', function(){
        console.log("I lost a client");
    });

});

Although it may seem like a simple query, I have exhaustively searched through various resources online but to no avail. Any assistance or guidance on this matter would be greatly appreciated. Thank you in advance!

Answer №1

Here is a solution that will solve the problem:

function _convertArrayBufferToBase64(buffer) {
    var binaryData = '';
    var bytesArr = new Uint8Array(buffer);
    var length = bytesArr.byteLength;
    for (var j = 0; j < length; j++) {
        binaryData += String.fromCharCode(bytesArr[j]);
    }
    return window.btoa(binaryData);
}

socket.onmessage = function (event) {
    var jsonObj = JSON.parse(event.data);
    if (jsonObj.task == "display-image") {
        var imagePath = _convertArrayBufferToBase64(jsonObj.data.imageData);
        document.querySelector("#ImagePreview").src = "data:image/jpeg;base64," + imagePath;
        var msg = JSON.stringify({"task": "fetch-image", "data": ""});
        socket.send(msg);
    }
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discovering the initial word of a string using jQuery

I'm currently facing an issue with jQuery that I need help solving. Here's the scenario: I am creating tooltips and positioning them directly under a specific trigger using CSS. Everything is functioning correctly, but there is one problem: In ...

[entity: undefined prototype] { type: 'clip', info: 'Watch my latest video!!' } using nodejs - multer

import routes from "./routes"; import multer from "multer"; const multerVideo = multer({ dest: "videos/" }); export const localsMiddleware = (req, res, next) => { res.locals.siteName = "Webtube"; res.locals.routes = routes; res.locals.user = { isA ...

Tips on concealing and deactivating the fullscreen option in flowplayer

Could someone please assist me in resolving this issue? I've been attempting to hide the fullscreen button from the flowplayer, but so far, I haven't found a solution. Below is my JavaScript code: <script> $f("player", "flowplayer/flowpla ...

The pagination component in React with Material-ui functions properly on a local environment, but encounters issues when deployed

Looking for some assistance with a persistent issue I've run into. Can anyone lend a hand? [x] The problem persists in the latest release. [x] After checking the repository's issues, I'm confident this is not a duplicate. Current Behavior ...

What's causing my variables to be returned as null in the alerts?

Why am I receiving null values when alerting my variables? I'm attempting to pass a string stored in a variable from an external JavaScript file back to the main page using alerts. Initially, I suspected that the JavaScript was not fetching data cor ...

What is the best way to transform a for loop using array.slice into a for-of loop or map function in order to generate columns and rows

Experiencing an issue with Angular8. Seeking help to convert a for loop for an array into a loop utilizing either for-of or array.map. The code in question involves passing an array of objects and the need to separate it into col and row arrays for visual ...

Importing data from a CSV file into a Google Spreadsheet using the Python programming language

I am currently working on a Python script to transfer data from a CSV file to a Google Spreadsheet. While I have a good grasp of the fundamentals required for this project, I am struggling with formatting and parsing the data from the CSV file into the Goo ...

Error Encountered During JavaScript Form Validation

Currently, I am troubleshooting a website that was created by another developer. There is a form with JavaScript validation to ensure data is accurately entered into the database. However, I am puzzled as to why I keep receiving these alert messages. Pleas ...

Tips for sending information to a JavaScript variable through AJAX requests

Hello there, I'm currently working on a project that involves posting data stored in a JavaScript variable using AJAX. Can anyone assist me with the correct syntax for this process? <div class="container-fluid"> <div class="card shadow m ...

Is it possible to utilize the spread operator for combining arrays?

Consider two different arrays represented by variables a and b. The variable c represents the output as a single array, indicating that this method combines two or more arrays into one. let a=[a ,b]; let b=[c ,d]; c=[a,...b] The resulting array will be: ...

The special function fails to execute within an "if" condition

As a newcomer to JavaScript/jQuery and Stack Overflow, I kindly ask for your patience in case there are any major errors in my approach. I am currently developing an HTML page with Bootstrap 3.3.7, featuring a pagination button group that toggles the visib ...

Having trouble with importing a variable in an Express application? You may encounter this error message: "Route.get() must

When trying to import requireSignin from the controllers/auth.js file into the routes/user.js file and adding it to the router.get('/user/:id', requireSignin, read); route, an error occurs: Error: Route.get() requires a callback function but r ...

Class variable remains unchanged following AJAX request

Upon completion of the ajax request, two integers are received - this.N and this.M. However, these values are not being set by the storeDims() function even though the correct decoding is done on the dims variable. This implies that I am unable to access ...

Working efficiently with query selectors in React using useRef

I have created a typewriting effect function and now I am trying to display the code associated with this effect within a specific div element (typingRef). Currently, I am using typingRef.current = letter, but I am wondering if this is equivalent to docu ...

Angularjs - Transferring the $scope object to a controller

While taking Angular's complimentary online course, I came across the following code snippet: app.controller('GalleryController', function(){ this.current = 0; this.setCurrent = function(imageNumber){ this.current = imageNumber || 0 ...

Is there a way for me to retrieve the value from an input, round it up to the nearest even number, and assign it to a new variable?

I am working on a project that involves two text boxes and a drop-down menu for providing rates. The values in the text boxes are given as inches. I want these inputs to be taken as values, rounded up to the next even number, and then set as variables. How ...

A code to ensure input values are always set to the maximum possible value

I recently developed a script that monitors the live value property of 3 <input> elements, correcting them if the live value is outside the specified range. However, I encountered an issue where the script automatically sets the value to the max as s ...

Running Python script in Node.js and pausing until completion

I am currently working on an API-Rest project using Node.js, where I need to run a python script that will create a .json file and store it in a specific directory. My goal is to wait for the python script to finish executing so that Node.js can access the ...

Execute the Angular filter again when there is a change in the scope

I am currently working on an application where Users have the ability to switch between kilometers and miles for unit distances. To handle this, I created a custom filter that converts the distances accordingly: app.filter('distance', function() ...

There was an issue with the Discord.js (v12) Giveaway Command that resulted in an error stating "Error: Cannot read property 'hasPermission' of undefined"

Hey everyone, I'm trying to develop my own Discord bot and I want to add a giveaway command to it. I found an example code online that I tried to implement, but unfortunately, it's not working as expected... const ms = require('ms'); c ...