How to convert image to Base64 and include in Json as result - json

newBie in asp.net WebApi.
1) How to resize an image and convert it to base64 and return it to Client.
2) I am not sure about the pro and con on base64 conversion vs byteArray for image.
3) Which format is better to use in webApi
return image in byteArray or Base64 in json.
understand these are allowable dataType. So, sending image bytes is not ok.
In JSON, values must be one of the following data types:
a string
a number
an object (JSON object)
an array
a boolean
null
I need fast processing for webApi.
Your help is greatly appreciated.
Thanks

You need to use atob to base64 decode and use btoa to encode
you need to Escape datas before to encode base64
function utf8_to_b64( str ) {
return window.btoa(unescape(encodeURIComponent( str )));
}
function b64_to_utf8( str ) {
return decodeURIComponent(escape(window.atob( str )));
}
// Usage:
var test1 = utf8_to_b64('✓ à la mode'); // "4pyTIMOgIGxhIG1vZGU="
var test2 = b64_to_utf8('4pyTIMOgIGxhIG1vZGU='); // "✓ à la mode"
console.log(test1);
console.log(test2)
base more complet for more type of data https://developer.mozilla.org/fr/Add-ons/Code_snippets/StringView

Related

Flutter - Convert "\x" encoded utf-8 characters to readable String from http.get response

I'm parsing a html page in my flutter app, and somewhere in the middle of that html source has a json string in utf-8 format ( "\x" format).
I'm able to get the html content and then parse to it extract that json object in "\x" utf-8 format to a String var, but I'm not able to convert it to a json to decode it.
I tried printing the ranes of that first 4 letters in that parsed output "\x5B" it printing as 4 separate ints, while the same "\x5B" I statically assigned to a String var and printed the ranes , it only shows one digit. So just wondering how can I decode that extracted String in "\x" format ?
An extract of the code as below:
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
var res = utf8.decode(response.bodyBytes);
//gives the starting index of json object in html source
int startIndex = res.indexOf('var statData');
// start and end index of json object in "\x" format
int start = res.indexOf("(", startIndex) + 2;
int end = res.indexOf(");", start) - 1;
//extract the json in \x encoded
String dataJson = res.substring(start,end);
//now sample code to compare the string, one statically assigned,
//another extracted from the html source, to describe the issue I'm having now.
String sample1 = dataJson.substring(0,4)); //extracts "\x5B" from the string
String sample2 = "\x5B";
print(sample2.runes); // prints (91)
print(sample1.ranes); // prints (92, 120, 53, 66), expectation is to get (91)
}
Output :
I/flutter ( 3437): (91)
I/flutter ( 3437): (92, 120, 53, 66)
While sample2.runes prints the single character (91)( equivalent ascii is '{' - start of the json)),
The same "\x5B" I extracted from the string not getting decoded as (91), instead it is treated as 4 separate characters, so looks like '\x' extracted string is not treated as utf-8 encode indicator.
I want the sample1.runes also to be {91}, how to approach this ?, where am I going wrong?
I don't know whether this is the correct way to handle it, but thanks to this post https://stackoverflow.com/a/64699290/17301137
, I was able to resolve it.
Basically It does a regex match of all Hex values after '\x' then replace it to corresponding string return.
final Pattern unicodePattern = new RegExp(r'\\x([0-9A-Fa-f]{2})');
final String newStr = sample1.replaceAllMapped(unicodePattern, (Match unicodeMatch) {
final int hexCode = int.parse(unicodeMatch.group(1)!, radix: 16);
final unicode = String.fromCharCode(hexCode);
return unicode;
});
this is the way I resolved it.
But not sure, whether there any better way to resolve it.

How do I get data from this json field?

How are you doing?
I'm trying to get data from a json to show on a screen that should be like the image below. I'm able to get most of the data, except for one field coded as String which consists of the image and a description like this one:
"lessonText": "{\"ops\":[{\"insert\":{\"image\":\"data:image/jpeg;base64,(IMAGE CODE HERE)=\"}},{\"attributes\":{\"color\":\"#444444\"},\"insert\":\"(LESSON TEXT HERE)\"},{\"insert\":\"\\n\"}]}",
How do I extract data from here? I have tried to convert this to a Map but it is not working.
Thanks for the help!
Something in line with this should give you the image
// json string containing the base64 image string
String jsonString = "{\"ops\":[{\"insert\":{\"image\":\"data:image/png;base64,(IMAGE CODE HERE)=\"}},{\"attributes\":{\"color\":\"#444444\"},\"insert\":\"(LESSON TEXT HERE)\"},{\"insert\":\"\\n\"}]}";
// convert the string to a map structure
Map<String, dynamic> json = jsonDecode(jsonString);
// extract the image string
String imageString = json['ops'][0]['insert']['image'];
// extract the base64 string
var prefix = "data:image/png;base64,";
var imageBase64String = imageString.substring(prefix.length);
// decode the base 64 string
var bytes = base64Decode(imageBase64String);
// build the image widget from bytes
var imageWidget = Image.memory(bytes);
As I mentioned in the comments, use a combination of decoding the base64 string to bytes and then loading the image from memory. See the the relevant documentation for base64Decode and Image.memory. If you would like a full code sample just let me know and I would be happy to throw one together.
Note: you should run the base64Decode method asynchronously, as it may take some time to decode an entire image (especially on lower-end hardware).

parsing JSON on appcelerator

i have a webservice like this:
{"person":{"name account":"Jhon Doe","Image":"image/test","Adress":"New York 43","Recomendations":"40"}}
this is what i'm trying to do, when i print datos i get the whole json but when i try to print just the name or Image i don't get anything
var urll = "example.com/example";
var json;
var xhrr = Ti.Network.createHTTPClient({
onload: function() {
json = JSON.parse(this.responseText);
var datos = JSON.stringify(json);
var medicos = datos;
Ti.API.info("Json! "+datos);
}
});
xhrr.open('GET', urll);
xhrr.send();
i tried with datos[0].person, datos.person but nothing
You have to understand the difference between a string that contains a JSON representation of an object - and the object itself.
Your json variable contains the object (which is what JSON.parse(...) does - convert a text string to an object). On the object you can refer to the attributes as you discovered. You can do this in two ways:
json.person.Address
json.person['name account']
I would suggest that you try to avoid attributes with names that are not valid identifiers (as the latter of the two) as this makes it a little more difficult to use them - e.g. by not allowing the dot notation.
Your datos variable on the other hand contains the string representation of the json object (as JSON.stringify(...) does exactly that - convert an object to its string representation). This means that datos is the same as this.responseText (since you first parse it and then stringify it back).
So JSON.stringify(...) is a brilliant way to make the object "human readable" but you need the object to work with the data.
Hope this clarifies the terms a little ;-)
/John
i just find the solution:
Ti.API.info("Json! "+json.person.Recomendations);

Generate a JSON object form a the value of another JSON in WP8

I am working on a WP8 app. In this I need to connect to web services whose results will be some JSON. I was trying to extract some data from the result that the web service provide. I was able to extract from the initial JSON response. But I need to get some data from the value of one such key . SO I tried to generate another Json object from it. But I m stuck. please help.Please find my example code below(I am using Newtonsoft.JSon).
private void messages_buttons_Click(object sender, RoutedEventArgs e)
{
var str = "{'status': '0', 'result': '%7B%22campaign_id%22%3A%221%22%2C%22tfn%22%3A%2218773374136%22%2C%22campaign_code%22%3A%22PJC%22%2C%22ad_id%22%3A%221%22%2C%22qr_url%22%3A%22http%3A%5C%2F%5C%2F1d1.us%5C%2FPJC%5C%2F%22%2C%22campaign_name%22%3A%22PJ+Test+Campaign%22%2C%22is_active%22%3A%221%22%2C%22expire_on%22%3A%222021-05-05+00%3A00%3A00%22%2C%22start_on%22%3A%222021-05-05+00%3A00%3A00%22%2C%22alias%22%3A%22%22%2C%22icon_image_url%22%3A%22products%5C%2Fpjc%5C%2Fpjc3.jpg%22%2C%22fb_page_url%22%3A%22https%3A%5C%2F%5C%2Fwww.facebook.com%5C%2FJackLaLannePowerJuicerssfb%22%2C%22video_url%22%3A%22http%3A%5C%2F%5C%2Fyoutube.com%5C%2Fembed%5C%2FyZPedpRA9r0%3Fshowinfo%3D0%26autoplay%3D1%26loop%3D1%26playlist%3DyZPedpRA9r0%22%2C%22url%22%3A%22https%3A%5C%2F%5C%2Fwww.facebook.com'}";
JObject ne = JObject.Parse(str);
var x= (ne.GetValue("result")).ToString();
var z = x.Replace("%", "");
JObject newest = JObject.Parse(z);
var y = newest.GetValue("campaign_id");
MessageBox.Show(y.ToString());
}
I get an exception at "JObject newest = JObject.Parse(z);" with the message
Unexpected character encountered while parsing number: m. Path '', line 1, position 6.
Am I doing it entirely wrong?
On a general note: can I convert a value from one Json to a another JSOn Itself? i.e if the value of one json key is a string with some key value pairs, can i make a json object on that string?
You can't actually just remove the % chars to get a valid value. You need to decode the string.
If you use this:
HttpUtility.UrlDecode(x);
You'll find your "result" is actually invalid JSON:
{"campaign_id":"1","tfn":"18773374136","campaign_code":"PJC","ad_id":"1","qr_url":"http://1d1.us/PJC/","campaign_name":"PJ
Test Campaign","is_active":"1","expire_on":"2021-05-05
00:00:00","start_on":"2021-05-05
00:00:00","alias":"","icon_image_url":"products/pjc/pjc3.jpg","fb_page_url":"https://www.facebook.com/JackLaLannePowerJuicerssfb","video_url":"http://youtube.com/embed/yZPedpRA9r0?showinfo=0&autoplay=1&loop=1&playlist=yZPedpRA9r0","url":"https://www.facebook.com
So hacking the value to make it valid JSON might work for you, by adding the missing "} at the end should turn your value in to valid JSON and allow you to parse it.
JObject newest = JObject.Parse(x + "\"}");
var y = newest.GetValue("campaign_id");
It doesn't appear that z is a valid json object at this point. It is only the value of result. Try something like JObject.Parse("'result':" + z);

Strange Base64 encode/decode problem

I'm using Grails 1.3.7. I have some code that uses the built-in base64Encode function and base64Decode function. It all works fine in simple test cases where I encode some binary data and then decode the resulting string and write it to a new file. In this case the files are identical.
But then I wrote a web service that took the base64 encoded data as a parameter in a POST call. Although the length of the base64 data is identical to the string I passed into the function, the contents of the base64 data are being modified. I spend DAYS debugging this and finally wrote a test controller that passed the data in base64 to post and also took the name of a local file with the correct base64 encoded data, as in:
data=AAA-base-64-data...&testFilename=/name/of/file/with/base64data
Within the test function I compared every byte in the incoming data parameter with the appropriate byte in the test file. I found that somehow every "+" character in the input data parameter had been replaced with a " " (space, ordinal ascii 32). Huh? What could have done that?
To be sure I was correct, I added a line that said:
data = data.replaceAll(' ', '+')
and sure enough the data decoded exactly right. I tried it with arbitrarily long binary files and it now works every time. But I can't figure out for the life of me what would be modifying the data parameter in the post to convert the ord(43) character to ord(32)? I know that the plus sign is one of the 2 somewhat platform dependent characters in the base64 spec, but given that I am doing the encoding and decoding on the same machine for now I am super puzzled what caused this. Sure I have a "fix" since I can make it work, but I am nervous about "fixes" that I don't understand.
The code is too big to post here, but I get the base64 encoding like so:
def inputFile = new File(inputFilename)
def rawData = inputFile.getBytes()
def encoded = rawData.encodeBase64().toString()
I then write that encoded string out to new a file so I can use it for testing later. If I load that file back in as so I get the same rawData:
def encodedFile = new File(encodedFilename)
String encoded = encodedFile.getText()
byte[] rawData = encoded.decodeBase64()
So all that is good. Now assume I take the "encoded" variable and add it to a param to a POST function like so:
String queryString = "data=$encoded"
String url = "http://localhost:8080/some_web_service"
def results = urlPost(url, queryString)
def urlPost(String urlString, String queryString) {
def url = new URL(urlString)
def connection = url.openConnection()
connection.setRequestMethod("POST")
connection.doOutput = true
def writer = new OutputStreamWriter(connection.outputStream)
writer.write(queryString)
writer.flush()
writer.close()
connection.connect()
return (connection.responseCode == 200) ? connection.content.text : "error $connection.responseCode, $connection.responseMessage"
}
on the web service side, in the controller I get the parameter like so:
String data = params?.data
println "incoming data parameter has length of ${data.size()}" //confirm right size
//unless I run the following line, the data does not decode to the same source
data = data.replaceAll(' ', '+')
//as long as I replace spaces with plus, this decodes correctly, why?
byte[] bytedata = data.decodeBase64()
Sorry for the long rant, but I'd really love to understand why I had to do the "replace space with plus sign" to get this to decode correctly. Is there some problem with the plus sign being used in a request parameter?
Whatever populates params expects the request to be a URL-encoded form (specifically, application/x-www-form-urlencoded, where "+" means space), but you didn't URL-encode it. I don't know what functions your language provides, but in pseudo code, queryString should be constructed from
concat(uri_escape("data"), "=", uri_escape(base64_encode(rawBytes)))
which simplifies to
concat("data=", uri_escape(base64_encode(rawBytes)))
The "+" characters will be replaced with "%2B".
You have to use a special base64encode which is also url-safe. The problem is that standard base64encode includes +, / and = characters which are replaced by the percent-encoded version.
http://en.wikipedia.org/wiki/Base64#URL_applications
I'm using the following code in php:
/**
* Custom base64 encoding. Replace unsafe url chars
*
* #param string $val
* #return string
*/
static function base64_url_encode($val) {
return strtr(base64_encode($val), '+/=', '-_,');
}
/**
* Custom base64 decode. Replace custom url safe values with normal
* base64 characters before decoding.
*
* #param string $val
* #return string
*/
static function base64_url_decode($val) {
return base64_decode(strtr($val, '-_,', '+/='));
}
Because it is a parameter to a POST you must URL encode the data.
See http://en.wikipedia.org/wiki/Percent-encoding
paraquote from the wikipedia link
The encoding used by default is based
on a very early version of the general
URI percent-encoding rules, with a
number of modifications such as
newline normalization and replacing
spaces with "+" instead of "%20"
another hidden pitfall everyday web developers like myself know little about