How to display raw image data with html and javascript? - javascript

I have an ajax application where the PHP side sends uncoded raw image data, coming from a camera, to the client javascript side.
I would like to display the image via html and javascript using img or canvas tags.
Image data are 32*32 unsigned char.
I would like to do, whatever it takes to reach my goal (encoding or everythig else), but I want to do it at client side beacause I cannot handle any other operation at the server side.
I tried to encode raw data into jpeg or png data but without success.
I post an example that doesn't work:
var encoder = new JPEGEncoder(9);
var jpgFile = encoder.encode(rawImage, 9);
document.getElementById("image").src = jpgFile;
jpgFile is like
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAFk9Q05DOFlOSE5kXllphd6QhXp6hf/CzaHe//////////////////////////////////////////////////8BXmRkhXWF/5CQ///////////////////////////////////////////////////////////////////////////AABEIAAAAAAMBEQACEQEDEQH/xAGiAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgsQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+gEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoLEQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/AP8A/9k=
I got JPEGEncoder googling on internet.

Tried it for you =)
http://jsfiddle.net/bYGum/
All you have to do is make sure your string is base64 encoded and do the exact same thing you have already written:
document.getElementById("image").src = jpgFile;

Related

Binary to Image in Javascript

I'm doing a project with Angular 8 where I need to get an image with binary format.
After my request I get a lot of data with this profil:
�PNG
IHDR�P�� -sBIT|d�tEXtSoftwaregnome-screenshot��> IDATx�
(a lot more data)
I want to display the image but I can't, I tried to use btoa() but the fonction return nothing, impossible to even do the log.
At the end after trying many things I have this
let test = encodeURIComponent(result.response);
console.log(test);
let img = "data:image/png;base64," + btoa(test);
vm.billData.image = img;
The image isn't showing anyway.
Can someone help me ?
I faced the same challenge in my previous project. I had to show a PDF file which i receive from server in the binary format. It worked After sending responseType:'blob' in request params

Convert Image to Memory Stream data in Javascript

I generate a qr code image using jquery.qrcode library. I get the image in the following format.
<img src="data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7"/>
I want to print this image with some text added to it(since this is a qrcode). I know to print the image when the image is drawn from backend of C#. Is there anyway I can convert this image to memory stream data to send to C# or anyway that I can print from Javascript when the image is drawn?
send your image base64 url using ajax call
on C# side use this function
public Image Base64ToImage(string base64String)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0,
imageBytes.Length);
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
return image;
}
You can print directly from JavaScript, you don't need to convert or send it to c#. The c# is in back-end, and I believe you need to print on the front-end (end-user machine)
You can use IFRAME and add the image your text to it.
After that you can print the IFRAME.
http://jsfiddle.net/8gcz0dw7/
A working Example
iframe=document.createElement('iframe')
document.body.appendChild(iframe)
var co=iframe.contentDocument.body;
$(co).append('your text<img src="data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7"/>')
iframe.focus()
iframe.contentWindow.print()

Upload photo into facebook from html5 canvas

In my jsp page, I have a manipulated photo within a html5 canvas and I want to upload it to facebook upon clicking the upload button.
FacebookType publishPhotoResponse = facebookClient.publish("me/photos", FacebookType.class,
BinaryAttachment.with("test.jpeg", getClass().getResourceAsStream("xxx")),
Parameter.with("message", "Test"));
out.println("Published photo ID: " + publishPhotoResponse.getId());
I am using Restfb for the uploading part in my servlet. However, I have no clue what attribute is needed for me to pass over to servlet side for processing (for example: "xxx"). When I used toDataURL, the URL of the image is base64. Does facebook api allows me to upload photo using the base64 format?
var base64URL = document.getElementById('canvasImg').src;
var decodedURL = escape(window.atob(base64URL));
alert(decodedURL);
The above coding seems to contain error as it won't display the alert. Should I decode the base64 data first before handling it over to servlet or should I pass the whole base64 data to servlet to handle the decoding?

Uploading JavaScript generated image to Django

I have an image generated on the client side which I want to transfer to the server through a form. For example, let's say that I have a registration form in which the profile image is generated automatically by JavaScript, and I want to transfer that image to django.
What is the best way to transfer the image binary data to the server when user hit the submit button? what form field should I use?
thanks!
Found an answer myself, here's the solution in case someone needs it:
In the client side, this is how you get the image from canvas and set it to a form field (a hidden char field):
var dataURL = document.getElementById('canvas_id').toDataURL("image/png");
document.getElementById('id_hidden_image_field').value = dataURL;
And in django side:
add to the form a hidden field called 'hidden_image_field', which will be used to pass the data. this field is a simple CharField. you can add max_length limit to make sure image is in a reasonable size (note: not dimensions but actual size).
to parse the image data:
import re
import base64
dataUrlPattern = re.compile('data:image/(png|jpeg);base64,(.*)$')
ImageData = request.POST.get('hidden_image_field')
ImageData = dataUrlPattern.match(ImageData).group(2)
# If none or len 0, means illegal image data
if (ImageData == None or len(ImageData) == 0:
# PRINT ERROR MESSAGE HERE
pass
# Decode the 64 bit string into 32 bit
ImageData = base64.b64decode(ImageData)
and now ImageData contains the binary data, you can simply save to a file and it should work.
hope this helps.

HTML syntax unknown to display a javascript binary string containing a jpeg image

I can't get through this problem though it must be only a very small syntax problem, as you will see: In fact, I'm searching for just a little piece of syntax, unless what I intend to do would be impossible (But I can see no reason why it should be impossible...).
I have written a function to encode an image into Base64 on server side, because I want to store numerous images into an array:
So, with Base64 I can download images as ordinary strings that I can organize in an array, then put them into an object just when I have chosen the right image and the right moment, without having to refer to the server again, so that the user doesn't have to wait.
Then I do something like this:
First phase:
function download64(imageUrl) //->string
{ // ask the server to send the 'imageUrl' as a base64 string
var tx = DoTheJob(); // ...connect through ajax and download the image converted in base64 as a string in var 'tx'
return tx
}
At this stage, I'm holding the image in the 'tx' Base64-string on client side.
Somewhat later I want to display my image in the div called "cadre", so I do the following:
Second phase:
I just have to call the "display64" function to set my image into the "cadre" div-object on the screen:
display64("cadre",tx);
using this function:
function display64(destinationDiv,imgText64) //->void
{ // display 'imgText64' into destinationDiv
var oImg = "<img alt='' src='data:image/jpg;base64," + imgText64 + "'>";
var x = document.getElementById(destinationDiv);
x.innerHTML = oImg;
}
Now the image is displayed. Unfortunately, this works well only with Firefox, because Internet Explorer 8 can't read Base64 images above 32Kb! And in my entreprise, we use IE 8 only!
Then I dropped my base64 encoder and decided to fetch the image as a binary string, which I could manage though I initially had a problem with nul character.
Now, I'm here with my binary string containing the exact copy of the source JPG file (including zeros that I have encoded on server side then restored on client side). So, what I need now is the simple function 'displayBin', but I can't find the syntax on the web:
function displayBin(destinationDiv,imgTextBin) //->void
{ // display 'imgTextBin' into destinationDiv
var oImg = "<img alt='' src='??????? + imgTextBin + "'>"; // What's the syntax here, please?
var x = document.getElementById(destinationDiv);
x.innerHTML = oImg;
}
Can anyone help ? Thanks a lot.
If I understand your question your are wanting to store images so you do not have to connect back with the server. One way of doing this is to preload the images like var img=new Image; img.src='path'; You could load all of the images into an array and you could then add them to the page as necessary. There is a lot out there on image preloading since that seems what your trying to accomplish.

Categories