How to encode UTF8 characters into Base64 in JavaScript - javascript

I tried like this when handling chinese, but the output is messy code garbled:
var a = "你好";
undefined
a
"你好"
a = unescape(encodeURIComponent(a));
"ä½ å¥½"
a
"ä½ å¥½"
compared to handling English:
var a = "Hello";
undefined
a
"Hello"
a = unescape(encodeURIComponent(a));
"Hello"
Here is my whole code:
var content = $("div#test").html();
content = unescape(encodeURIComponent( content ));
content = window.btoa(content);
content = "data:image/svg+xml;filename:{{ request.session.access_token.uid }}.svg;base64," + content;
UPDATED:
What I am trying to do is encoding a generated SVG as data url for user to download. I solved this problem by converting SVG to canvas (using CanVG) first and use html2canvas to generate base64 ... finally it works ...

Try roundtripping this, and it works fine:
decodeURIComponent(escape(window.atob(window.btoa(unescape(encodeURIComponent("‌​東京"))))))
Whether or not some intermediate result appears to be garbled is not relevant.
The problem with the window.btoa(decodeURIComponent(escape(unescape(encodeURIComponent("東京"))))) in one of the comments is the calls are not balanced and not in the right order.

Related

How to show binary photo inside <img> tag

I am wondering if there is a way to use binary photo that i get from a server.
So for example I have this kind of url mybackend.com/get_image?id=1 and as a response I get a photo.
This is the response that I console.log:
�PNG
IHDR
ռ��IDATx�� ���
U��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“E>�|�(�Q��G��“�HL}/�MwIEND�B`�
This value that i logged is binary i guess.
When I set <img src="mybackend.com/get_image?id=1" /> it works because browser first makes GET network call and makes this binary show probably under the hood.
I found bunch of answers regarding this and it usually says that I need to convert this into base64 and than insert it into src attribute. But they don't bring me near to showing photo.
Thanks
const base64Image = btoa(binaryImage);
const imageTag = `<img src="data:image/png,${base64Image}" />`
btoa has a caveat - the binary must have a specific string representation. The MDN article explains how to work around this:
// convert a Unicode string to a string in which
// each 16-bit unit occupies only one byte
function toBinary(string) {
const codeUnits = new Uint16Array(string.length);
for (let i = 0; i < codeUnits.length; i++) {
codeUnits[i] = string.charCodeAt(i);
}
return String.fromCharCode(...new Uint8Array(codeUnits.buffer));
}
// a string that contains characters occupying > 1 byte
const myString = "☸☹☺☻☼☾☿";
const converted = toBinary(myString);
const encoded = btoa(converted);
console.log(encoded); // OCY5JjomOyY8Jj4mPyY=
Though it may be easier to simply use a library which can do this out of the box, such as js-base64
<script src="https://cdn.jsdelivr.net/npm/js-base64#3.6.0/base64.min.js"></script>
Base64.fromUint8Array(binaryImage);

Angular add extra variable on Img at end %E2%80%8B

http://myimage.png%E2%80%8B
I have just copy paste this img url but it added some wiered data on end and image does not show . but on code it looks perfect .
I have tried something in Angular like
var imageSafeUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.imageLink);
this.imageLink = imageSafeUrl['changingThisBreaksApplicationSecurity'];
but still it adds
The data is url encoded so it can be typed safely in an address bar and interpreted by the browser/server
%E2 = â
%80 = `
%8B = ‹
A table to help you interpret the encoded characters is available at https://www.w3schools.com/tags/ref_urlencode.asp
So together you have copied http://myimage.pngâ`‹
Added "?" after link now Extra data is set as query parameter
<a title="GreenPop" href="http://myimage.png?" >

FileReader.readAsDataURL result returning format exception when entered in Convert.FromBase64String

I'm using the following to convert an image to a base64 encoded string. On the client website in javascript:
var reader = new FileReader();
reader.onloadend = function () {
data64 = reader.result;
};
reader.readAsDataURL(myFile);
Now I pass this data to the server, which does the following:
var data = Convert.FromBase64String(data64);
However this results in a format exception:
The format of s is invalid. s contains a non-base-64 character, more than two padding characters, or a non-white space-character among the padding characters.
My input file is one of the sample images found on Windows 7 -> My Pictures/Sample Pictures/Tulips.jpeg
How can I attempt to debug what is causing the problem for such a large result output?
Okay, I have worked around this by using reader.readAsBinaryString instead and then converting this using btoa.
This seems to be accepted fine in Convert.FromBase64String
I experienced the same issue and founds out that my complete dataurl contained not only padding characters at the end, but also padding characters in the middle of the dataurl.
I used the following code to fix the base64string (but it still has a bug):
private static string getCleanedBase64String(string base64String)
{
string tempString = base64String.Replace("_", "/").Replace("-", "+").Replace("=", "");
return tempString + new string('=', (4 - tempString.Length % 4) % 4);
}

How can I obfuscate a string in JavaScript?

Basically, I want to make a game in JavaScript and allow a user to get a copy paste-able code which stores their data. In reality, this "code" is actually obfuscated JSON that can be decoded by the application later.
I don't need much security, as I am aware that if people put some effort in they can view/modify the save, and I have no interest in stopping them. I just want the average user to not be tempted and/or see unnecessary information.
Thanks in advance.
you can use base64 encoding to encode your json String. it would be faster approach.
If you with pure javascript :
var encodedData = btoa("stringToEncode");
If you are using nodejs:
base-64 encoding:
var encodedStr = new Buffer("Hello World").toString('base64')
decode to original value:
var originalString = new Buffer("SGVsbG8gV29ybGQ=", 'base64').toString('utf-8')
Well... given that there is no security concern and you only want users to see what appears to be garbled data you can "encode" all the json data
var jsonData = {"key":"value"};
// turn it into a string
var jsonString = JSON.stringify(jsonData);
// replace some letters
var awkardString = jsonString.replace(/a/g, '!Ax6'); // be carefull, you should replace a letter with a pattern that does not already exist on the string.
// encode it with some type of reversible encoding
var garbledData = encodeURI(jsonString);
// output is: %7B%22key%22:%22v!Ax6lue%22%7D
// to "decode" it do the same steps in reverse
awkardString = decodeURI(garbledData);
jsonString = awkardString.replace(/!Ax6/g, 'a'); // now you see, if '!Ax6' existed on the source string, you would loose it and get an 'a' in return. That is why the replacement should be as unique as possible
jsonData = JSON.parse(jsonString);

html entities in a javascript alert?

I have a string coming from a XML (which I can't edit) and I'd like to print it trough an alert in javascript.
Example of my string:
This is à string
And I need to print in an alert:
This is à string
is there a js html decode?
you could put the string in a dom element and read it out again, even without jquery:
https://stackoverflow.com/a/3700369/1986499
Edit by recent demand to include some code from another SO answer:
var div = document.createElement('div');
div.innerHTML = encoded;
var decoded = div.firstChild.nodeValue;
var encoded = "This is à string";
var decoded = $("<div/>").html(encoded).text();
alert(decoded);
I'm just a tiny bit late, but just in case anyone else finds this via Google (like I did), I thought I'd improve upon Imperative's answer.
function showbullet() {
var tempelement = document.createElement('div');
tempelement.innerHTML = "•";
alert("Here, have a bullet!\n" + tempelement.innerHTML);
}
showbullet();
I've tested this and confirmed it works in Chrome/43.0.2357.130 m; Firefox/32.0.1; Internet Explorer/9.0.8112.16421. There's no need to go mucking about with nodeValue's and what not; the entity will be replaced with it's associated character as soon as the assignment is complete. (Note, however, that doing alert(tempelement.innerHTML="•"); does not work in any of the browsers I tested!)

Categories