Base64 decode in javascript and encode in php - javascript

I am facing a major issue in encoding/decoding a base 64 image.
My purpose is to save a canvas image as base64 decoded string that can later be base64 encoded in php.
I have the javascript code as follows:
var string= canvas.toDataURL("image/jpeg");
var abc = window.atob(string.split(",")[1]);
var blob = "HEADERS"+abc;
blob is the file.
PHP code:
$Data = blob File
$img = substr($Data, $start, $end);
$img = base64_encode($img);
I start when I find chr(0xFF) . chr(0xD8) in the blob file and end when I find chr(0xFF) . chr(0xD9)
These characters are not found when I decode through javascript but easily gets found when using base64_decode of php. There is a problem of encoding type I think and I'm a novice in the encoding methods. so kindly help.

Related

Decode in JavaScript encoded Base64 value in PHP

I'm trying to decrypt "window.btoa" in PHP, please see my PHP code in below.
<script>
var url = "?url=";
var input = 'some text';
var encrypt = window.btoa( input );
var link = "www.domain.com/"+url+encrypt;
</script>
My Link generated as below
www.domain.com/?url=c29tZSB0ZXh0
PHP code in below
<?php
$testURL = $_GET['url'];
echo $testURL;
?>
Please guide me how to decrypt this value.
The Javascript btoa function will encode your string to base-64. To decode the result in PHP use the base64_decode function;
<?php
echo base64_decode('c29tZSB0ZXh0');
?>
Will print;
some text
btoa is not encryption, it is encoding, it is Base64 encoding badly named: Base64 uses the "A-Z", "a-z", "0-9", "+", "/" and "=" characters to encode the string.
See Window btoa() Method, first hit on Google for "window.btoa".
Using Base64 -> hexadecimal string decoder c29tZSB0ZXh0 is decoded to hex: 736F6D652074657874 and text: some text.

Sending "windows-1251"-encoded string in JSON from python to javascript

What I need to do is best descriped as example.
Previously, I had the following code:
content = u'<?xml version="1.0" encoding="windows-1251"?>\n' + ... #
with open(file_name, 'w') as f:
f.write(content.encode('cp1251'))
f.close;
Now I want to modify the architecture of my entire app and send the string which is supposed to be the file content to client via JSON and to generate the file via javascript.
So, now my code looks something like this:
response_data = {}
response_data['file_content'] = content.encode('cp1251')
response_data['file_name'] = file_name
return JsonResponse({'content':json.dumps(response_data, ensure_ascii=False)}) # error generated
The problem is that I get UnicodeDecodeError: 'ascii' codec can't decode byte 0xd4 in position 53: ordinal not in range(128)
I also tried the second option this way:
response_data = {}
response_data['file_content'] = content
response_data['file_name'] = file_name
return JsonResponse({'content':json.dumps(response_data, ensure_ascii=False).encode('utf8')}) # error generated
Then, on client, I try to covert utf8 to windows-1251.
$.post ('/my_url/', data, function(response) {
var file_content = JSON.parse(response.content).file_content;
file_content = UnicodeToWin1251(file_content);
...but...I get distorted symbols.
I know I am doing something terribly wrong here and am likely to mess up things with encoding, but still it's been an entire day I couldn't solve this issue. Could someone give a hint where my mistake is ?
Both XML and JSON contain data that is Unicode text. The XML declaration merely tells your XML parser how to decode the XML serialisation of that data. You wrote the serialisation by hand so to match the XML header, you had to encode to CP-1251.
The JSON standard states that all JSON should be encoded in either UTF-8, UTF-16 or UTF-32, with UTF-8 the standard; again, this is just the encoding for the serialisation.
Leave your data as Unicode, then encode that data to JSON with the json library; the library takes care of ensuring you get UTF-8 data (in Python 2), or gives you Unicode text (Python 3) that can be encoded to UTF-8 later. Your Javascript code will then decode the JSON again at which point you have Unicode text again:
response_data = {}
response_data['file_content'] = content
response_data['file_name'] = file_name
return JsonResponse({'content':json.dumps(response_data, ensure_ascii=False)})
There is no need whatsoever to send binary data over JSON here, you are sending text. If you Javascript code then generates the file, it is responsible for encoding to CP-1251, not your Python code.
If you must put binary data in a JSON payload, you'll need to encode that payload to some form of text. Binary data (and CP-1251-encoded text is binary data) could be encoded in text as Base-64:
import base64
response_data = {}
response_data['file_content'] = base64.encodestring(content.encode('cp1251')).decode('ascii')
response_data['file_name'] = file_name
return JsonResponse({'content':json.dumps(response_data, ensure_ascii=False)})
Base64 data is encoded to a bytestring containing only ASCII data, so decode it as ASCII for the JSON library, which expects text to be Unicode text.
Now you are sending binary data, wrapped in a Base64 text encoding, to the Javascript client, which now has to decode the Base64 if you need the binary payload there.

convert binary data to base-64 javaScript

I have a problem to convert binary data to base-64 in JS.
I try all the things that exists on the net include this How to parse into base64 string the binary image from response?, but everyone return a wrong base-64 and I don't find why !
**I try this solution Retrieving binary file content using Javascript, base64 encode it and reverse-decode it using Python but the convert to base-64 not work for me! It's return something wrong .
I get a string binary response from server and I want to convert him to base-64 that I can create a file from him and to show him to user.
This is the response I get from server to png picture for example:
�PNG
IHDRrP6�tEXtSoftwareAdobe ImageReadyq�e<�IDATx�b���?�#6��g��T=;��� >č�&g��:��A�#���LX��0�A�T >[40f��H��>0`B
#��<��0a�+���b�
�o����­o0��~�7��'�xlP����e��.3<x��A�����~�w��$�#90���
`���Ivd�1#c�2���F&�ATM��.�p���[���8��p�]�#,�����pyP��q���pB����u�����3l(6A `#􁳟qzK�Q���M�8Q�Ӑ&��1�$(�#� R�81H��P�&P�����ҟ1\��V��3P�d��fp0�#;��ld �yt�(����
J{�М��>>#{!А�3%?#/�
0�O�U,{�9IEND�B`�
Now , I want to take this binary string and to convert him .
For example , the real base 64 of png picture is:
iVBORw0KGgoAAAANSUhEUgAAABMAAAATCAYAAAByUDbMAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAaJJREFUeNpi/P//PwO1ACM2wf9njBWAVD0QOwCxApLUAyA+AMSNjCZnH6DoATqKEYtB/UCqgAiHTAAaWIjTMKBB84FUAgk+WwA0MBFmGBOaixJIDKYEqD4wYEIKI7DXHjz/xTBh+SuGD5//YtUNkm+c9Zzhwq1vMKECqH6IN5G9J+h4AWxQgIMAw/oeZQzDFP0uMzx49otBgJeZ4f1+A7h3GYzPJLJAOQEw0fn1CmCFuADIAgVJdmSXMUBjHe4yyhOb8RlGJqBBDlRNtMgu23DgA8PFW98Z9NU4weGGDnDKA10GC7MPQCwAiqnAkrtweVDYGahxwfmgcEKO5fubdYHhxwbTzwAzbAMoNkESIANgGkD0gbOfcXpLgAceURvg6QwIFsITTaQ4UeHTkCaFHOsLMfIkKOxAuCBSDBSGODFIHqYWlgNQ8iZQEBSa+4HYAJHSnzFcuPkdHFagsDNQ52SI9xFmcDDmhQcjEDsC8+cHbBkdZCCxeXQCtCj6gLMIghoKSnvx0JyBnD4+QAN7IdCQAwTLMxwFJQg/QC8Q0Q0DCDAA/k/PVSx73TkAAAAASUVORK5CYII=
When I use any kind of code to convert to base-64 it's return this string :
77+9UE5HDQoaCgAAAA1JSERSAAAAEwAAABMIBgAAAHJQNu+/vQAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHvv71lPAAAAe+/vUlEQVR477+9Yu+/ve+/ve+/vT8D77+9ACM277+977+9Z++/vRXvv71UPRA7AO+/vQLvv73vv70DID4AxI3vv70mZx/vv73vv70BOu+/vRHvv71B77+9QO+/ve+/vQjvv71MABpY77+977+9MO+/vUHvv73vv71UAgk+WwA0MBFmGBPvv73vv70SSAzvv70E77+9PjBgQgoj77+977+9Hjzvv73vv70wYe+/vSvvv70P77+977+9Yu+/vQ3vv71v77+977+977+977+9wq1vMO+/vQLvv71+77+9N++/ve+/vSfvv714AWxQ77+977+9AO+/ve+/vR5lDO+/vRTvv70uMzx477+977+9Qe+/ve+/ve+/ve+/ve+/vX4D77+9dxnvv73vv70k77+9QDkBMO+/ve+/ve+/vQpg77+977+9AO+/vQIFSXZk77+9MUBjHe+/vTLvv70T77+977+9GUYm77+9QQ5UTe+/ve+/vS7vv71w77+9A++/ve+/vVvvv70Z77+977+9OO+/ve+/ve+/vQ5w77+9A10GC++/vQ9ALADvv73vv73vv73vv73vv71weVDvv70Z77+9ce+/ve+/ve+/vXBC77+977+977+977+9de+/ve+/ve+/vQbvv73vv70AM2wDKDZBEiADYBpA9IGzn3F6S++/vQceURvvv73vv70MCBbvv70TTe+/vThR77+905Am77+9HO+/vQsx77+9JCjvv71A77+9IFIMFO+/vTgxSB7vv70W77+9A1Dvv70mUBAU77+977+977+977+9AO+/vdKfMVzvv73vv70dHFbvv73vv70zUO+/vWTvv73vv70RZnAw77+977+9ByMQOwLvv73vv70HbBkdZCDvv715dALvv70o77+977+977+9CO+/vRoKSnvvv73QnO+/ve+/vT4+QAN7IdCQAwTvv70zHAUlCD9ALxDvv70NAwgwAO+/vU/vv71VLHvvv705AAAAAElFTkTvv71CYO+/vQ==
I find this solution for encode to base 64 : https://koding.com/Activity/base64-encoding
And now the encode is closer to what need to be but still not help:
/VBORw0KGgoAAAANSUhEUgAAABMAAAATCAYAAAByUDb9AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5cf1lPAAAAf1JREFUeP1i/f39PwP9ACM2/f1n/RX9VD0QOwD9Av39AyA+AA39Jmcf/f0BOv0R/UH9QP39CP1MABpY/f0w/UH9/VQCCT5bADQwEWYYE/39EkgM/QT9PjBgQgoj/f0ePP39MGH9K/0P/f1i/Q39b/39/f2tbzD9Av1+/Tf9/Sf9eAFsUP39AP39HmUM/RT9LjM8eP39Qf39/f39fgP9dxn9/ST9QDkBMP39/Qpg/f0A/QIFSXZk/TFAYx39Mv0T/f0ZRib9QQ5UTf39Lv1w/QP9/Vv9Gf39OP39/Q5w/QNdBgv9D0AsAP39/f39cHlQ/Rn9cf39/XBC/f39/XX9/f0G/f0AM2wDKDZBEiADYBpAx99xekv9Bx5RG/39DAgW/RNN/ThR/dAm/Rz9CzH9JCj9QP0gUgwU/TgxSB79Fv0DUP0mUBAU/f39/QD9nzFc/f0dHFb9/TNQ/WT9/RFmcDD9/QcjEDsC/f0HbBkdZCD9eXQC/Sj9/f0I/RoKSnv9HP39Pj5AA3shEAME/TMcBSUIP0AvEP0NAwgwAP1P/VUse/05AAAAAElFTkT9QmD9
I try also the soultions here:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data without convert to base-64 and with 'arrayBuffer' and 'Blob' objects but the picture didn't show . The only way the picture show it's when I convert to a correct base-64 and then create arraybuffer and initialize Blob with him .
But the problem is the same - I cant convert my data to correct base-64.
can anyone save me please ??
Thanks !
Here is the link to this small library that is meant can be useful for u. It can convert base64 to binary and vice versa.
My problem is solved . I use dropzone plugin to get the response from server and because of this I get binary data as a text reponse and it make my problems. I just go to dropzone.js and change 2 minor things to get the response in type of arraybuffer :
xhr.responseType = 'arraybuffer'; ( line 1246)
This is new line to get the response in type of arrayBuffer, and then create a Blob object from the arraybuffer response .
response = xhr.response; (line 1305 )
Change it to get response inseted TextRrsponse..
I hope that it will help somebody...
Thanks everyone !
You could try using the turbocommons library. Just download the minified js file (turbocommons-es5.zip) and write the following code:
<script src="../yourpathtothelibrary/turbocommons-es5.js"></script>
<script>
var ConversionUtils = org_turbocommons.ConversionUtils;
ConversionUtils.stringToBase64('your binary string here');
</script>
I believe it will work in your case as it is extensively tested, Or you can look at the code on how it is done by the library here:
https://github.com/edertone/TurboCommons/blob/master/TurboCommons-TS/src/main/ts/utils/ConversionUtils.ts
More info here:
https://turboframework.org/en/blog/2022-10-26/encode-decode-base64-strings-javascript-typescript-php
Or you can test it online here:
https://turboframework.org/en/app/stringutils/base64-encode

Display byte array in html without conversion to Base64 string

I know that it is possible to display byte arrays as images in html after conversion to Base64 string as explained: Here
Is it possible in html to display the raw byte array as Image without conversion to string?
the window.URL.createObjectURL Method creates a URL for the byte array image directly without conversion
var link = window.URL.createObjectURL(data);
var image = document.getElementById("liveBox");
image.src = link;

Convert Base64 to image file with javascript

Does anyone know of any simple javascript that I can use to turn a base64 string into an image (jpg format preferably), so that I can save the image to a file? This is for a signature pad application. I can get the signature into a base64 format, but need to save the signature as an image file to use for embedding into a Crystal Report.
I have tried this method in a JSP page to print the image from a base64 string, I guess this should hold good for javascript too. Do not have sample data for now to verify, but here's how I would try it.
var oImg=document.createElement("img");
var baseString = null; //the base64 string you have
var imsc = 'data:image/jpg;base64, '+baseString;
oImg.setAttribute('src', imsc);
document.body.appendChild(oImg);

Categories

Resources