Use image data from XMLHttpRequest responsetext to display image - javascript

I'm using JavaScript to get an image from the XMLHttpRequest response text and set the image src to it:
document.getElementById("img").src = "data:image/png;base64," + xhr.responseText;
From the nodejs script, the image is sent like:
var img = fs.readFileSync('image.png');
res.end(img, 'base64');
The response text doesn't come in base64 and has weird symbols:
�PNG���IHDR���������,���2PLTE
�������������������������#����Ai���
...
I found this question and tried to convert it to base 64:
for (var responseText = xhr.responseText, responseTextLen = responseText.length, bin = "", i = 0; i < responseTextLen; ++i) {
bin += String.fromCharCode(responseText.charCodeAt(i) & 255);
}
document.getElementById("img").src = "data:image/png;base64," + btoa(bin);
The result was:
img id="img"
src="data:image/png;base64,/VBORw0KGgoAAAANSUhEUgAAAv0AAAH9CAMAAAACDyz9AAABMlBMVEX9/f0AAAD9/f39AAAA/QAA/f39AP0A/f39QAD9/QBBaf39/SAA/UD9/f0wYP39AABA/QD9/f1//SUqKv39AED9/QAAABoaGjMzM01NTWZmZn9/f/39/f39/f39/f39/f39/f39/f0yMv0t/f39Vf39/f39Qv39/f39/f39AAD9AABkAAD9fyL9Ii79VwAA/QAA/RkZcAAA/QAAR/39AP39/QD9AP39/RT9/X9Q/f39/UUA/f1y/Xr9Pf1r/f0L/f0g/SD9/QD9/QD9YFBQQFVrL/0UAP0UFP1AFP1A/f1g/f1g/f39AP39QP39QP39YP39cP39/f39/f39/Xf9/f39/f39/f39/Xz9QP39IP39/f39/V9fXx8fHz8/P/39/f39/VFqAAAMV0lEQVR4/f39C1b9/Rr9URhV/Qo6/Qf9fxf9AR8I/SH9C/39Dv39/Tb9VyH9/f1sAAAAAAAAAAD9N2j9/f14a3j9/Q5l/f39dv39/bD9S/1vdAxwzh/9fXRR/f39Af39/f39C/39dAz9O2z9DV79/W7T/W9//f0RIFFe/f39/RP9/f1qAv39MEz9a3L9/f39LDP9/TQLUhT9Vwf9/WIR/QZZ/RhP/SD9/f1Y/X5xKi79/f39/Wn9/Vn9/f1b/WYR/WVB/WX9/Vn9HxAgd/39/f1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9/TN+/f19OwtX/f1+/X0Z/f39IzhZ/f39eH/9fv1p/f0w/S79fH/9cmwKHv39Z/3X/f39/f39PP39/VtzH/0vFP03tXP9THz9fv39S/1VT/1ybCoe/f1n/Xj9a/39JPtWPP1faP39Uf39KSYg/f39/Vt5/f0H/f39Af39/XT9If3yFP39Pv0OWwn9/VH9/QAv/S8wbTFmP/01/VH9VDwz/f39Tf17fP39D1H9/V79Bv1+GP0z/Wn9/U9YEP39/WL9T3+j/QH9eWb9/Sf9bgIe/f39/SJvX/0eXv39/f0//f39L3X9C0xS/Tj9Xv39B/39/R0j/f0GXCb9/VT9bv1m/f0Y/S/9/f39/WVrXin9/WP9S/39Hf39/XH9/VH9/QT9BT9m/f39/f39Yf39/f0F/VH9PDP9/Xh8/f0ZPy79E/0vWP0f/f0HX/1+/f39BXX9W/39/VQ8M1Vr/QUP/Wz9/U1D/f13/f0FCv39vW9h/RZT/TP9cv1x/Rk//f0H/Tf9eP0pGGj9Nnf9/QUK/Rh9b2H9/VD9MzP9VP3GAv39AAAAAAAAAAAA/Sf9H0o3/f1y/VL9AAAAAElFTkT9QmD9">
The image still doesn't show. What am I doing wrong?

It sounds like you're looking for buf.toString([encoding][, start][, end]).
Consider the following code:
var fs = require('fs');
var base64_image = fs.readFileSync('image.png').toString('base64');
console.log(base64_image);
This will return image.png as a base64 encoded string in the console.
So you probably want to remove that for () loop and change:
var img = fs.readFileSync('image.png');
To this:
var img = fs.readFileSync('image.png').toString('base64');
I hope that helps!

As Dal suggested, I did the base64 encoding on the server side:
var img = fs.readFileSync('plot.png', 'base64');
res.end(img);
I added the 'base64' encoding option to the readFileSync() instead of the res.end() so img would get sent as a string instead of a buffer as described here.
On the client side, I used this:
document.getElementById("img").src = "data:image/png;base64," + xhr.responseText;

Related

Sending image from server to client via base64 encoding

I'm facing an issues sending an Image (np.ndarray) over my python server to my javascript client.
Starting with the python server, I process the img like this:
1) Load img as np.ndarray
2) enc_img = base64.b64encode(img.copy(order='C'))
3) utf8_img = enc_img.decode("utf-8")
4) json = {
...
"img": utf8_img,
...
}
5) req_return = json.dumps(json, ensure_ascii=False)
// The fct below I found on SO ..
For the client (javascript) I do the following:
function b64EncodeUnicode(str) {
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
return String.fromCharCode(parseInt(p1, 16))
}))
}
img_64 = b64EncodeUnicode(jsonRes.fs_dict.face)
var src = "data:image/jpg;base64,";
src += img_64;
var newImage = document.createElement('img');
newImage.src = src;
newImage.width = newImage.height = "100";
document.querySelector('#face_img').innerHTML = newImage.outerHTML;
To sum it up, I want to send an image over the API and convert it into a valid base64 format to display via html. After experimenting a little I sometimes got "no valid base64 format" but with the provided code I'm not getting any error. The image doesn't show up though.
It is important to not save the file in my scenario.
So I figured the problem. I had troubles encoding the image (nparray) to a proper base64 encoding.
pil_img = Image.fromarray(nparray_img)
buff = BytesIO()
pil_img.save(buff, format="JPEG")
enc_img = base64.b64encode(buff.getvalue()).decode("utf-8")
this resolved the encoding issues for me.
I then return a dictionary containing the img like so:
res = {
"img": enc_img
}
return res
After converting it to JSON via
json.dumps(res), I send it via the API to my JavaScript Client.
When receiving the JSON, I first parse it to access the dictionary again like so:
jsonRes = JSON.parse(xhr.responseText);
img = jsonRes.img;
and finally output it via HTML by using jQuery:
var source = "data:image/jpg;base64,";
source += img;
$(document).ready(function() {
$('#face_img').attr('src',source).height(100).width(100).show();
});
The
('#face_img')
is an ID of my HTML, looking like the following:
<img id="face_img" src="" alt="img_face" />
Hope this helps someone.

Use the base64 preview of the binary data response (zip file) in angularjs

I always get this error in the downloaded zip file C:\Users\me\Downloads\test.zip: Unexpected end of archive
My current code is:
var blob = new Blob([data], { // data here is the binary content
type: 'octet/stream',
});
var zipUrl = window.URL.createObjectURL(blob);
var fileName = orderNo;
fileName += '.zip';
downloadFile(null, fileName, null, zipUrl, null); // just creates a hidden anchor tag and triggers the download
The response of the call is a binary (I think). Binary Content Here
But the preview is a base64. Base64 Content. And it is the correct one. The way I verify it is by using this fiddle.
You can refer to the screenshot of the network here
I put the base64 content in this line var sampleBytes = base64ToArrayBuffer(''); And the zip downloaded just opens fine.
Things I have tried so far.
Adding this headers to the GET call
var headers = {
Accept: 'application/octet-stream',
responseType: 'blob',
};
But I get Request header field responseType is not allowed by Access-Control-Allow-Headers in preflight response.
We're using an already ajax.service.js in our AngularJS project.
From this answer
var blob = new Blob([yourBinaryDataAsAnArrayOrAsAString], {type: "application/octet-stream"});
var fileName = "myFileName.myExtension";
saveAs(blob, fileName);
There are other things that I have tried that I have not listed. I will edit the questions once I find them again
But where I'm current at right now. The preview is correct base64 of the binary file. Is it possible to use that instead of the binary? (If it is I will not find the other methods that I've tested) I tried some binary to base64 converters but they don't work.
So I just went and ditched using the ajax.service.js, that we have, for this specific call.
I used the xhr snippet from this answer. I just added the headers necessary for our call: tokens and auth stuff.
And I used this code snippet for the conversion thing.
And the code looks like this:
fetchBlob(url, function (blob) {
// Array buffer to Base64:
var base64 = btoa(String.fromCharCode.apply(null, new Uint8Array(blob)));
var blob = new Blob([base64ToArrayBuffer(base64)], {
type: 'octet/stream',
});
var zipUrl = window.URL.createObjectURL(blob);
var fileName = orderNo;
fileName += ' Attachments ';
fileName += moment().format('DD-MMM-YYYY');
fileName += '.zip';
downloadFile(null, fileName, null, zipUrl, null); // create a hidden anchor tag and trigger download
});
function fetchBlob(uri, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', uri, true);
xhr.responseType = 'arraybuffer';
var x = AjaxService.getAuthHeaders();
xhr.setRequestHeader('auth_stuff', x['auth_stuff']);
xhr.setRequestHeader('token_stuff', x['token_stuff']);
xhr.setRequestHeader('Accept', 'application/octet-stream');
xhr.onload = function (e) {
if (this.status == 200) {
var blob = this.response;
if (callback) {
callback(blob);
}
}
};
return xhr.send();
};
function base64ToArrayBuffer(base64) {
var binaryString = window.atob(base64);
var binaryLen = binaryString.length;
var bytes = new Uint8Array(binaryLen);
for (var i = 0; i < binaryLen; i++) {
var ascii = binaryString.charCodeAt(i);
bytes[i] = ascii;
};
return bytes;
}

Store image content not image path in mongodb

I have seen many questions and solutions for this now. I am new to Mongo DB and MEAN stack development. I want to know whether there is anyway to store image content itself rather than path of the image file in Mongo DB. All the solutions suggests to store image as buffer and then use it back in the source by converting buffer to base64. I did it but the resulting output get resolves to path to the image file rather than the image content. I am looking to save image itself in DB.
// saving image
var pic = {name : "profilePicture.png",
img : "images/default-profile-pic.png",
contentType : "image/png"
};
//schema
profilePic:{ name: String, img: Buffer, contentType: String }
//retrieving back
var base64 = "";
var bytes = new Uint8Array( profilePic.img.data );
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
base64 += String.fromCharCode( bytes[ i ] );
}
var proPic = "data:image/png;base64," + base64;
console.log(proPic);
//console output
data:image/png;base64,images/default-profile-pic.png
The output for proPic resolves to "data:image/png;base64,images/default-profile-pic.png"
few links that I referred before posting this
How to do Base64 encoding in node.js?
How to convert image into base64 string using javascript
The problem is simply, that you don't read and encode the picture. Instead you use the path as a string.
Serverside using Node
If you want to perform it on the serverside with an image on the filesystem you can use something along following:
var fs = require('fs');
// read and convert the file
var bitmap = fs.readFileSync("images/default-profile-pic.png");
var encImage = new Buffer(bitmap).toString('base64');
// saving image
var pic = {name : "profilePicture.png",
img : encImage,
contentType : "image/png"
};
....
Clientside
Again we need to load the image and encode it as base64. There is an answer about doing this on the client here.
using the first approach the result would be something like following:
function toDataUrl(url, callback, outputFormat){
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function(){
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.height;
canvas.width = this.width;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
canvas = null;
};
img.src = url;
}
toDataUrl("images/default-profile-pic.png", function(encImage){
// saving image
var pic = {name : "profilePicture.png",
img : encImage,
contentType : "image/png"
};
//Proceed in the callback or use a method to pull out the data
....
});
Below two links saved my time. If we use "ng-file-upload" our life becomes easy from there.
https://github.com/danialfarid/ng-file-upload#install
https://github.com/danialfarid/ng-file-upload
Below is what worked for me
//my html code
<div>
<button type="file" ngf-select="onFileSelect($file)" ng-model="file" name="file" ngf-pattern="'image/*'"
ngf-accept="'image/*'" ngf-max-size="15MB" class="btn btn-danger">
Edit Profile Picture</button>
</div>
//my js function
function onFileSelect(file){
//var image = document.getElementById('uploadPic').files;
image = file;
if (image.type !== 'image/png' && image.type !== 'image/jpeg') {
alert('Only PNG and JPEG are accepted.');
return;
}
$scope.uploadInProgress = true;
$scope.uploadProgress = 0;
var reader = new window.FileReader();
reader.readAsDataURL(image);
reader.onloadend = function() {
base64data = reader.result;
$scope.profile.profilePic = base64data;
ProfileService.updateProfile($scope.profile).then(function(response){
$rootScope.profile = response;
$scope.profilePicture = $rootScope.profile.profilePic;
});
}
}
// when reading from the server just put the profile.profilePic value to src
src="data:image/png;base64,{base64 string}"
// profile schema
var ProfileSchema = new mongoose.Schema({
userid:String,
//profilePic:{ name: String, img: Buffer, contentType: String },
profilePic:String
}
I wouldn't say this is the best solution but a good place to start.Also this limits you from uploading file size more than 16 MB in which case you can use"GridFs" in the above implementation initially the file is converted to "blob" and then I am converting it to "base64" format and adding that to my profile's string variable.
Hope this helps someone in saving their time.

Cropit upload canvas image to NodeJS

I am trying to upload a cropped image with the Cropit jQuery plugin which uses the canvas in the front end. Basically trying to recreate process described here:
How to crop and upload photo using cropit jquery plugin with php
My Node.js effort:
var img = //DATA RECEIVED FROM THE POST REQUEST
var decoded = decodeURIComponent(require('url').parse(img, true).path.replace(/\++/g, ' '))
var exp = decoded.replace('data:image/jpeg;base64','').split(',');
var base64 = exp.shift();
var data = base64url.decode(base64);
fs.writeFile('./public/woooo.jpg', data,function(err,done){
if (err){
console.log(err)
}
})
The result is an image file which cannot be opened. Why? What am I doing wrong? Anyone else has managed this?
Found it:
var decoded = decodeURIComponent(require('url').parse(img, true).path.replace(/\++/g, ' '))//base64url.decode(img);
var exp = decoded.split(',');
var base64 = exp.shift();
var data = base64url.decode(base64);
var data_c = data.replace('data:image/jpeg;base64,','')
var buffer = new Buffer(data_c, 'base64');
fs.writeFileSync('./public/woo.jpg', buffer);

Using JavaScript to display a Blob

I am retrieving a Blob image from a database, and I'd like to be able to view that image using JavaScript. The following code produces a broken image icon on the page:
var image = document.createElement('image');
image.src = 'data:image/bmp;base64,'+Base64.encode(blob);
document.body.appendChild(image);
Here is a jsFiddle containing all the code required, including the blob. The completed code should properly display an image.
You can also get BLOB object directly from XMLHttpRequest. Setting responseType to blob makes the trick. Here is my code:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost/image.jpg");
xhr.responseType = "blob";
xhr.onload = response;
xhr.send();
And the response function looks like this:
function response(e) {
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL(this.response);
document.querySelector("#image").src = imageUrl;
}
We just have to make an empty image element in HTML:
<img id="image"/>
If you want to use fetch instead:
var myImage = document.querySelector('img');
fetch('flowers.jpg').then(function(response) {
return response.blob();
}).then(function(myBlob) {
var objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
});
Source:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
You can convert your string into a Uint8Array to get the raw data. Then create a Blob for that data and pass to URL.createObjectURL(blob) to convert the Blob into a URL that you pass to img.src.
var data = '424D5E070000000000003E00000028000000EF...';
// Convert the string to bytes
var bytes = new Uint8Array(data.length / 2);
for (var i = 0; i < data.length; i += 2) {
bytes[i / 2] = parseInt(data.substring(i, i + 2), /* base = */ 16);
}
// Make a Blob from the bytes
var blob = new Blob([bytes], {type: 'image/bmp'});
// Use createObjectURL to make a URL for the blob
var image = new Image();
image.src = URL.createObjectURL(blob);
document.body.appendChild(image);
You can try the complete example at: http://jsfiddle.net/nj82y73d/
In your example, you should createElement('img').
In your link, base64blob != Base64.encode(blob).
This works, as long as your data is valid http://jsfiddle.net/SXFwP/ (I didn't have any BMP images so I had to use PNG).
I guess you had an error in the inline code of your image.
Try this :
var image = document.createElement('img');
image.src="data:image/gif;base64,R0lGODlhDwAPAKECAAAAzMzM/////wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48CXF8m2iQ3YmmKqVlRtW4MLwWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw==";
image.width=100;
image.height=100;
image.alt="here should be some image";
document.body.appendChild(image);
Helpful link :http://dean.edwards.name/my/base64-ie.html
In the fiddle your blob isn't a blob, it's a string representation of hexadecimal data.
Try this on a blob and your done
var image = document.createElement('img');
let reader=new FileReader()
reader.addEventListener('loadend',()=>{
let contents=reader.result
image.src = contents
document.body.appendChild(image);
})
if(blob instanceof Blob) reader.readAsDataURL(blob)
readAsDataURL give you a base64 encoded image ready for you image element () source (src)
The problem was that I had hexadecimal data that needed to be converted to binary before being base64encoded.
in PHP:
base64_encode(pack("H*", $subvalue))

Categories

Resources