How can I save image as base 64? - javascript

I am using phantom js to retrieve the image's strings and then I encode them with base 64.
var content = btoa(unescape(encodeURIComponent(imagestring)));
self.writeFile(pathToFolder + fileTitle, content);
But images are not displayed. It says they are damaged.
How can I save an image like that?

If you want save image as base64 with JavaScript, you can try with this code:
var fs = require('fs');
// string generated by canvas.toDataURL()
var img = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0"
+ "NAAAAKElEQVQ4jWNgYGD4Twzu6FhFFGYYNXDUwGFpIAk2E4dHDRw1cDgaCAASFOffhEIO"
+ "3gAAAABJRU5ErkJggg==";
// strip off the data: url prefix to get just the base64-encoded bytes
var data = img.replace(/^data:image\/\w+;base64,/, "");
var buf = new Buffer(data, 'base64');
fs.writeFile('image.png', buf);

Related

Issue in decoding in node js

I have a requirement where I need to encode data in "iso-8859-1" and then convert back it to readable string in node js.
In .Net env:
string encodedData = "VABpAG0AZQAgAHMAZQByAGUAaQBzAA==";
Encoding encoding = Encoding.GetEncoding("iso-8859-1"); // encoding in "iso-8859-1"
byte[] = decodedbuff = convert.FromBase64String(encodedData); // getting buffer
result = encoding.GetString(decodedbuff); //decoding
result = timesereis
In a similar way, I need to encode and decode in node js
In Node js(using iconvlite)
const data = "VABpAG0AZQAgAHMAZQByAGUAaQBzAA=="
const buffer = iconvlite.encode(data,'iso-8859-1');
const result = buffer.toString('utf8');
Here in result, I am getting "VABpAG0AZQAgAHMAZQByAGUAaQBzAA==" instead of decoded result
By using the following code you get your desired result
let buffer = new Buffer(data, 'base64');
let result = buff.toString('utf-8');
console.log("result: "+text)

JAVASCRIPT decode a base64string (which is an encoded zipfile) to a zipfile and get the zipfiles content by name

the question says it all, im receiving a base64 encoded ZIPFILE from the server, which I first want to decode to a ZIPFILE in memory and then get the ZIPFILES content, which is a json-file.
I tried to use JSZIP but im totally lost in this case ... the base64 string is received with javascript by a promise.
So my question in short is: How can I convert a base64 encoded ZIPFILE to a ZIPFILE in memory to get its contents.
BASE64 -> ZIPFILE -> CONTENT
I use this complicated process to save much space on my database. And I dont want to handle this process on server-side, but on clientside with JS.
Thanks in advance!
If anyone is interested in my solution to this problem read my answer right here:
I received the data in a base64-string format, then converted the string to a blob. Then I used the blob-handle to load the zipfile with the JSZip-Library. After that I could just grab the contents of the zipfile. Code is below:
function base64ToBlob(base64) {
let binaryString = window.atob(base64);
let binaryLen = binaryString.length;
let ab = new ArrayBuffer(binaryLen);
let ia = new Uint8Array(ab);
for (let i = 0; i < binaryLen; i++) {
ia[i] = binaryString.charCodeAt(i);
}
let bb = new Blob([ab]);
bb.lastModifiedDate = new Date();
bb.name = "archive.zip";
bb.type = "zip";
return bb;
}
To get the contents of the zipfile:
let blob = base64ToBlob(resolved);
let zip = new JSZip();
zip.loadAsync(blob).then(function(zip) {
zip.file("archived.json").async("string").then(function (content) {
console.log(content);
// content is the file as a string
});
}).catch((e) => {
});
As you can see, first the blob is created from the base64-string. Then the handle is given over to the JSZip loadAsync method. After that you have to set the name of the file which you want to retrieve from the zipfile. In this case it is the file called "archived.json". Now because of the async("string") function the file (file contents) are returned as a string. To further use the extracted string, just work with the content variable.

createObjectUrl for binary data fails

In my javascript I have a base64 encoded pkcs12 object, which I want to provide as download link. The Pkcs12 (pfx) file to be downloaded is binary data.
So I decoded the object and tried to create an objectUrl from it:
var bin = atob(pkcs12);
var blob = new Blob([bin],
{ type : 'application/x-pkcs12' });
$scope.pkcs12Blob = (window.URL || window.webkitURL).createObjectURL( blob );
The problem is, that the downloaded file is bigger than the original binary data and is not recognized as pkcs12. It looks like as if some utf-8/unicode stuff was introduced into the file.
If I provide the original base64 encoded data to the createObjectURL and download the base64 encoded file, I can decode the downloaded file and get a valid p12 file.
So I am wondering: How does createObjectURL work for binary data?
For some reason createObjectURL does not accept a binary string but requires a byte array. This code worked like a charm:
var bytechars = atob($scope.enrolledToken.pkcs12);
var byteNumbers = new Array(bytechars.length);
for (var i = 0; i < bytechars.length; i++) {
byteNumbers[i] = bytechars.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var blob = new Blob([byteArray], {type: 'application/x-pkcs12'});
$scope.pkcs12Blob = (window.URL || window.webkitURL).createObjectURL( blob );

Json to excel file convert using javascript

Please find the following code for more information.
function dataToCSVTry(arr) {
var fileName = "CSVFile";
var data = "";
for (var i = 0; i < arr.length; i++) {
data += (arr[i].id + " , " + arr[i].time + "\r\n");
}
var url = 'data:text/csv;charset=utf8,' + encodeURI(data);
window.open(url, '_blank');
window.download = (url + ".txt");
var encodedUri = encodeURI(url);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "my_data.csv");
link.click();
};
`
This is a function to which I'm providing JSON data as input and after that trying to convert it in to a CSV(Comma Separated Values) using a for loop.
After that i am trying to save it in both .txt and .csv format. As .txt is getting saved easily, the problem comes in excel file where the data comes like :
"1%20%2C%20161.963%0A%0D%0A2%20%2C%20473.222%0A%0D%0A3%20%2C%20error%0A%0D%0A"
where some code (from what I think) is for blank space("%20%2C%20") and some other code("%0A%0D%0A") is for newline characters. What needs to be done in order to create Excel file in the same CSV format? Is there any problem with the encodeURI part that I am using ?
Data url content isn't URI encoded, it is base-64 encoded. You should use btoa or a similar solution to create your data from the CSV string you built.

JS open file from blob

I have a JavaScript method that asynchronously accepts a blob of an ms-word document. How can I open this as a word doc? I've tried:
function openDocAsync(blob) {
var wblob = new Blob([blob], { type: "application/msword" });
var status = navigator.msSaveOrOpenBlob(wblob);
}
I've also tried using:
var bb = new MSBlobBuilder();
bb.append(blob);
var nblob = bb.getBlob();
Neither to any avail. With the first option, msSaveOrOpenBlob, I can get Word to open a file of gibberish (base 64 encode of the binary), but not the desired contents.
How can I create a new Word doc using the blob supplied?
Thanks in advance

Categories