How to display a JPG image from a Node.js buffer (UInt8Array) - javascript

I have a custom Node.JS addon that transfers a jpg capture to my application which is working great - if I write the buffer contents to disk, it's a proper jpg image, as expected.
var wstream = fs.createWriteStream(filename);
wstream.write(getImageResult.imagebuffer);
wstream.end();
I'm struggling to display that image as an img.src rather than saving it to disk, something like
var image = document.createElement('img');
var b64encoded = btoa(String.fromCharCode.apply(null, getImageResult.imagebuffer));
image.src = 'data:image/jpeg;base64,' + b64encoded;
The data in b64encoded after the conversion IS correct, as I tried it on http://codebeautify.org/base64-to-image-converter and the correct image does show up. I must be missing something stupid. Any help would be amazing!
Thanks for the help!

Is that what you want?
// Buffer for the jpg data
var buf = getImageResult.imagebuffer;
// Create an HTML img tag
var imageElem = document.createElement('img');
// Just use the toString() method from your buffer instance
// to get date as base64 type
imageElem.src = 'data:image/jpeg;base64,' + buf.toString('base64');

facepalm...There was an extra leading space in the text...
var getImageResult = addon.getlatestimage();
var b64encoded = btoa(String.fromCharCode.apply(null, getImageResult.imagebuffer));
var datajpg = "data:image/jpg;base64," + b64encoded;
document.getElementById("myimage").src = datajpg;
Works perfectly.

You need to add img to the DOM.
Also if you are generating the buffer in the main process you need to pass it on the the render process of electron.

Related

How download base64 data as image?

I use vue-signature Library and I Don't know how to download base64 data generated as image,
Here is Link of library : https://www.npmjs.com/package/vue-signature
I've already read the documentation and see That "Save()" Methods Save image as PNG/JPG… but it give me base64 data,
thank you for your collaboration, I use vue js
This is not the most optimized solution, But it works.
var a = document.createElement("a"); //Create <a>
a.href = "data:image/png;base64," + ImageBase64; //Image Base64 Goes here
a.download = "Image.png"; //File name Here
a.click(); //Downloaded file
In your case you can try this
var canvas = document.querySelector("canvas");
var signaturePad = new SignaturePad(canvas);
// Returns signature image as data URL (see https://mdn.io/todataurl for the list of possible parameters)
signaturePad.toDataURL("image/jpeg"); // save image as JPEG
source : https://vuejsexamples.com/vue-signature-pad-component/

image onload not firing javascript when source is base64 websocket data

I have a Custom helpdesk application that I am trying to run in javascript.
the program has a peice of code that runs on the customer's computer and sends an image to a autobahn websocket server which acts as a proxy to a image viewer which can send clicks and keystrokes back over the websockets. this is all currently working in python correctly however, when i try it in javascript, I cannot get my image loaded no matter what I do and I can't figure out what i am doing wrong.
This is the part of my javascript that is broken:
function onMessage(evt) {
if(evt.data.indexOf('[00000]')>=0){
var ar = evt.data.split('[00000]');
if (ar[0] == "[IMAGE]"){
var imgdata = evt.data.split('[22222]');
context.width = imgdata[0];
context.height = imgdata[1];
console.log(context.width + " " + context.height)
try{
var img = new Image();
img.src = imgdata[2];
context.drawImage(img,0,0);
console.log("IMAGE");
}catch(e){
console.log(e)
}
}else if(ar[0] == "[RETCONN]"){
console.log("Accepted!");
}
}
}
Below is some code from the server to try and clarify what is going on with the javascript.
def onMessage(self, payload, isBinary):
if isBinary:
print("Binary message received: {0} bytes".format(len(payload)))
else:
msg = payload.decode('utf8')
com, data, arg = msg.split('[11111]')
if com == ("[IMAGE]"):
for name, conn in clients.items():
if name == data:
conn.sendMessage(('[IMAGE]'+'[00000]'+arg).encode('utf8'))
break
and this is how the image is put together from the customer side:
data = image.tostring()
data = base64.b64encode(data)
self.sendMessage(('[IMAGE]' + '[11111]' + rid + '[11111]' + str(w) + '[22222]' + str(h) + '[22222]' + data).encode('utf8'))
Anyone have any ideas how what i am doing wrong in my javascript?
EDIT: i am aware that img.src is in the wrong location. moving to the right spot does not fix the issue
If you want to use base64 encoded image as a source for the image object, it needs to be in format:
data:image/png;base64,<base64 encoded image>
You need to prepend data:image/png;base64, to your base64 string
img.src = "data:image/png;base64,"+imgdata[2];
You are also parsing your messages wrong.
imgdata[0] is supposed to be your width, but it also includes [IMAGE][00000].
You probably want ar[1].split('[22222]'); instead of evt.data.split('[22222]');.
To avoid complications with encoding, I would recommend you to use JSON to encode your WebSocket messages.
Edit:
You are getting a broken image because image.tostring() returns raw image data, but with data:image/png;base64, it's expected to be in PNG format.
To get base64 encoded PNG data use this:
import io
buffer = io.BytesIO()
image.save(buffer, "png")
data = base64.b64encode(buffer.getvalue())

Getting image file size transferred with socket.io

in a Node.js with Socket.io project, i get an image via Socket.io like this:
socket.on('newImage', function (data) {
var desc = data.description;
var image = data.img; //i want file size of this
}
in this code, image variable contains image binary data, i want to detect file size of that image. how?
Depending on how the data is encoded you can retrieve the byte length by using the byteLength method:
var encoding = 'binary';
var data = new Buffer('hello world', encoding);
Buffer.byteLength(data, encoding); // 11

svg to png not working, suspect svg element differences

Im having trouble figuring out why two different svg's would cause my javascript to work in one instance, but not in the other. I have only swapped out the svg elements in both examples, one works, one does not. Here is the code in two jsFiddles. The working example I got from here.
Ultimately, my goal is to save the current svg element of the floor plan, and insert the converted png as an inline img inside a rich text area. As if you took a cropped screenshot of the floor plan, and pasted it into a rich text area like you see in helpdesk sites. Im just having trouble converting to png.
Working: JsFiddle
Not Working: JsFiddle
Here is the js, i cant add the svg code or it will put me over the character limit of Stackoverflow.
var svgString = new XMLSerializer().serializeToString(document.querySelector('#svg2'));
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var DOMURL = self.URL || self.webkitURL || self;
var img = new Image();
var svg = new Blob([svgString], {
type: "image/svg+xml;charset=utf-8"
});
var url = DOMURL.createObjectURL(svg);
img.onload = function() {
ctx.drawImage(img, 0, 0);
var png = canvas.toDataURL("image/png");
document.querySelector('#png-container').innerHTML = '<img src="' + png + '"/>';
DOMURL.revokeObjectURL(png);
};
img.src = url;
Edit:
I have since settled on this code omitting the png/canvas conversions, and trying to place the serialized string of the svg, directly to the rich text area, but it gets an error in IE, Non-default namespace declarations must not have an empty URI. Line: 1, column142
var svgString = new XMLSerializer().serializeToString(document.querySelector('#svg2'));
var img = new Image();
var url = "data:image/svg+xml; charset=utf8, "+encodeURIComponent(svgString);
img.onload = function() {
document.querySelector('.ze_body').innerHTML = '<img src="'+url+'"/>';
};
img.src = url;
Also i think it would help if i showed more of the structure of how this rich text area currently sits. This is not our doing, its a product we use, and im just trying to get maps to paste into the description area so it can live with the ticket. Only access we have is js triggered from rules in the form.
Screenshot of ze_body element as it stands in the DOM
It comes from your namespace declaration :
Change xmlns:NS1="" NS1:xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:NS2="" NS2:xmlns:cc="http://creativecommons.org/ns#" xmlns:NS3="" NS3:xmlns:dc="http://purl.org/dc/elements/1.1/"
to xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/"> and it should work.
Also note that since you are using XMLSerializer().serializeToString(), you don't need to create a blob and an objectURL, you can only pass data:image/svg+xml; charset=utf8, " and the encodeURIComponent(svgString) as the url of your image. (fiddle).
ps: You can read about namespace declaration here.

How to Process a Byte Array Image in Javascript Produced by ASP.NET Response.BinaryWrite

I'm attempting to consume server-side code that is owned by another team and that I can't easily change. It is processing an image and returning it via Response.BinaryWrite:
MemoryStream ms = new MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
var imageToReturn = ms.ToArray();
Response.ContentType = "image/jpg";
Response.BinaryWrite(imageToReturn);
However, when I attempt to do standard client-side processing of the result, like using Javascript's btoa() to convert it from a byte array to an ArrayBuffer, I get messages like "'btoa' failed: The string to be encoded contains characters outside of the Latin1 range".
I really just want to be able to display and work with this image - so any approach that would get it to appear in a canvas, or convert it to a data URL, etc., would help me out. Am I missing something?
If you just want to display the image, why don't you just src attribute of img tag to the url of the ASP.Net page, which is writing the JPG in the in the response.
If you want to display the image in canvas, you can do it in following way
myimage = new Image();
myimage.onload = function () {
var canvas = document.getElementById('canv');
var ctx = canvas.getContext('2d');
ctx.drawImage(myimage, x, y);
}
myimage.src = '<url to the asp.net page>';

Categories

Resources