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

Firestore javascript query is returning empty results

Yesterday everything was working smoothly, but this morning it suddenly stopped moving forward. The Firestore query is not returning anything - no errors, no response. Surprisingly, the console displays the phone perfectly fine. Additionally, the phone n ...

Change the value in the array to match the value at the corresponding index in a different array

Consider the following array: $items = array([0] => Apple, [1] => Orange, [2] => Orange, [3] => Strawberry, [4] => Orange, [5] => Mango, [6] => Orange, [7] => Strawberry, [8] => Orange, [9] => Orange, [10] => Orange); The ...

Guide to switching classes with jquery

On my webpage, I have a star rating system that I want to toggle between "fa fa-star" and "fa fa-star checked" classes. I found some information on how to do this here: Javascript/Jquery to change class onclick? However, when I tried to implement it, it di ...

Is there a way to access an object stored on my server using JavaScript?

In implementing JavaScript, I wish to define two objects stored in a file named file.txt, and utilize them within my code. For instance, I have included the following snippet in my index.php: var counter = Number(localStorage.getItem('rans')) ...

Sveltejs template not displaying on M1 MacBook Air after running - stuck on blank screen

Currently, I am in the process of learning Sveltejs and have been utilizing for the tutorial, which has been quite effective. However, I decided to work on developing and testing Sveltejs applications locally on my MacBook Air M1. I downloaded the provid ...

Storing HTML elements in a database using jQuery's html() method

I have encountered a dilemma that has left me stumped after extensive online research. I have a dynamically generated webpage and need to save the entire appended body of the page to a database using PHP and MySQL. My current approach involves using the fo ...

Looking to alter the CSS of an ID element when hovering over a link on your website?

Irrespective of the positioning of the links in the html, a simple hover effect can trigger changes like switching images or altering backgrounds anywhere on the website. The ideal solution would involve a straightforward method without the need for Javas ...

Retrieve the radio button value from the HTML form

This website is designed to calculate ideal weight based on input data, but I am encountering an issue with the gender selection. The code seems to only recognize the first condition for female, while ignoring the else if condition for male. How can I fix ...

Is it possible to add animation to an SVG filter to create a captivating rotating planet with color effects?

I've added a filter to my self-created SVG and I'm interested in animating it so that the colors move diagonally, giving the appearance of a spinning planet. Below is the code featuring my SVG and how I'd like it to begin with the blue colo ...

leveraging third party plugins to implement callbacks in TypeScript

When working with ajax calls in typical javascript, I have been using a specific pattern: myFunction() { var self = this; $.ajax({ // other options like url and stuff success: function () { self.someParsingFunction } } } In addition t ...

The mouseenter event in jQuery is failing to trigger

I'm encountering an issue with the mouseenter event on a div section of my webpage. I am attempting to alter the background color of this div when the mouse enters, but it seems to be disregarded. This is the basic HTML code: <div id="services" c ...

What is the best way to invoke a Rest API within a Vue component?

As a newcomer to VueJS, my goal is to create a basic page featuring a pie chart displaying some data. Currently, I have successfully displayed the chart using example data. However, I now wish to populate the chart with data fetched from an API call on my ...

Is it necessary to specify a data type for the response when making an AJAX POST request?

After carefully reviewing my code, I have ensured that all the variables in my JavaScript match and are properly set up. Additionally, I have confirmed that all the variables in my data array for my AJAX request correspond correctly to my $_POST['var& ...

Is there a way to assign a value to an Angular-specific variable using PHP?

In the development of my Angular 4 application, I encountered an issue while receiving JSON data based on an id value through a PHP script. Upon examining the code, it seems that there should be a value passed into this.PropertiesList. examineProperties(i ...

Alter the value of an input element using JavaScript

There are multiple hidden input fields on the page I'm currently working on: <input a1="2" a2="1" a3="3" name="Value" type="hidden" value="10"> <input a1="4" a2="2" a3="6" name="Value" type="hidden" value="12"> <input a1="6" a2="3" a3 ...

Troubleshooting a Non-Responsive React onClick Event in ES6

I am a beginner in React and have been searching on various platforms like StackOverflow and the internet, but I cannot figure out why onClick is not working in my case. When I click the button, absolutely nothing happens. I have tried everything from putt ...

Using JQuery validate to extract the interest rate from a regular expression

I am looking for a regular expression that can extract the interest rate. I need it to accept values such as: Examples: 0 0.4 0.44 4 44 4.00 44.00 4.2 4.22 44.22 Minimum value allowed is 0 and maximum is 99.99 The regular expression should be ab ...

Attempting to understand how to retrieve specific items from my MongoDB Database that are associated with a particular user based on their ID

I've been attempting to retrieve specific items (Portfolio pics) that have been submitted by a user from my Mongo Database. However, when I checked the extracted items using Console logs, it seems to display all portfolio pieces for every user instead ...

When attempting to retrieve a data object using a Vuex action, I encounter an "Uncaught (in promise) TypeError" when trying to access the data within the object

Recently, I've been diving into Vuex and its actions for fetching data. While everything seems to be working smoothly - accessing the films object, selecting films from it - I encounter an error when trying to access specific data within a film. Vuex ...

What is the best way to create a delay in user hover activation before triggering a slideDown

In my current code snippet, I have implemented the functionality to perform a slideDown action when a user hovers over an element. However, I would like this slide down effect to only occur if the user has hovered for at least 2 seconds. If the user does n ...