I'm facing a tremendous problem using the base64 convertor. I am calling the standard base64 convert function on Windows Phone but the result always differs from the one expected on web converters and many other on Android and iOS platforms.
Basically I take an Image from the gallery or Camera and convert it to byte array. The the byte array is passed to convert method.
Convert.ToBase64String(bytearray);
The resulting string should look like this :
/9j/4AAQSkZJRgABAQEASABIAAD//gATQ3JlYXRlZCB3aXRoIEdJTVD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBT/wgARCAADAAMDAREAAhEBAxEB/8QAFAABAAAAAAAAAAAAAAAAAAAABv/EABUBAQEAAAAAAAAAAAAAAAAAAAUG/9oADAMBAAIQAxAAAAFMVff/xAAVEAEBAAAAAAAAAAAAAAAAAAAEBf/aAAgBAQABBQIlxoS//8QAGhEAAAcAAAAAAAAAAAAAAAAAAAEEFVKh0f/aAAgBAwEBPwFrSQs9H//EABcRAAMBAAAAAAAAAAAAAAAAAAADE1H/2gAIAQIBAT8BszT/xAAbEAACAgMBAAAAAAAAAAAAAAABAwISAAQRIf/aAAgBAQAGPwJOsl1EpgFwjUHgHgz/xAAZEAACAwEAAAAAAAAAAAAAAAABEQAhMUH/2gAIAQEAAT8hwppWyGQzQ7P/2gAMAwEAAgADAAAAEJ//xAAUEQEAAAAAAAAAAAAAAAAAAAAA/9oACAEDAQE/ECH/xAAXEQEAAwAAAAAAAAAAAAAAAAABANHw/9oACAECAQE/ENAqf//EABgQAQEAAwAAAAAAAAAAAAAAAAERACEx/9oACAEBAAE/EOKqRz0uAFSs2rn/2Q==
But the result is being this
/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAADAAMDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD7d+FP7cn7UvwM+F/w5+Cfws+KJ8LfDH4PeBPCXwt+HPhn/hCvh3rf/CO+BPh/oNh4T8I6H/bPiLwlq/iDV/7J0DSdPsDqmu6rqes6gbf7XqmoXt9NPcylFFfy7/b+e/8AQ6zb/wAOOM/+XH+2X/EKfC7/AKNtwD/4h3Dv/wA7j//Z
It differs not so much, but it differs.
The right one is generated using PHP. And the Windows phone is generated usingUNICODE encoding on image.
Does anyone know how where could be a problem?
Try using this piece of code using the WriteableBitmap:
public string GetBase64Encoding(BitmapImage imageUrl)
{
byte[] bytearray = null;
using (MemoryStream ms = new MemoryStream())
{
if (imageUrl == null)
{
}
else
{
WriteableBitmap wbitmp = new WriteableBitmap((BitmapImage)imageUrl);
wbitmp.SaveJpeg(ms, 46, 38, 0, 100);
bytearray = ms.ToArray();
}
}
string str = Convert.ToBase64String(bytearray);
return str;
}
For more you could refer this too:
Convert base64 string to image in C# on Windows Phone
Hope it helps!
Related
I use List & Label to generate various reports from database content. The output is handeled by a middleware service which receives the data as Json payload.
Up to now I did not manage to display images/pictures in reports such as i.e. an Itempicture on a customer quotation.
Does anyone may know, which graphic format is expected by the report designer picture object and/or which function might have to be used?
Drawing({String}) expects a path to a physical image file -> hence can not use it because the image data is available as kind of raw image text.
Any help ist highly appreciated.
It will work, if you handle this points:
the field within the JSON need to be base64 encoded - you can get it like this:
using (var memory = new MemoryStream())
{
using (var picture = new Bitmap(<YOURPIC>))
{
picture.Save(memory, System.Drawing.Imaging.ImageFormat.Jpeg);
var base64 = Convert.ToBase64String(memory.GetBuffer());
}
}
use the AutoDefineField-Event of the List & Label object and override FieldType for the matching picture field with its base64 content to LlFieldType.Drawing - e.g.:
private void LL_AutoDefineField(object sender, AutoDefineElementEventArgs e)
{
if (e.Name == "Contacts.myPic")
{
e.FieldType = LlFieldType.Drawing;
}
}
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).
I am trying to read a pdf from a URL, return it as a binary and replace some characters. This is working for plain text with the following code but if the pdf has any special symbols like Trademark, copyright etc then my webservice is unable to return the result. Can some one please help me how to achieve this. The output should definitely be a binary output :
String html="";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream in = new URL(jsonobj.getString("xBody")).openStream();
int reads = in.read();
while(reads != -1){
baos.write(reads);
reads = in.read();
}
html= baos.toString();
The method baos.toString() internally calls new String(buffer), which uses the default encoding (the encoding actually being used by your system, probably not UTF-8). Try to provide the encoding explicitly, as follows:
String html = new String(baos.toByteArray(), "UTF-8");
I need to store QML source code in a JSON file, in such a way that the formatting (newlines and spacing and whatnot) are preserved. I thought about programmatically inserting special unicode characters that I would never use in my source code as markers into the JSON (when saving it) to represent new lines and spaces. When reading the source code from JSON, I would replace these markers with either a newline or a space. However, this doesn't feel like a very robust solution.
Is there a better way to do this?
You can use QByteArray::toBase64() to convert the QML source to a string that can be saved to JSON:
void SourceCodeSerialiser::read(const QJsonObject &json)
{
mQml = QByteArray::fromBase64(json["qml"].toString().toUtf8());
}
And QByteArray::toBase64() to read the saved Base64 string back to a string of QML:
void SourceCodeSerialiser::write(QJsonObject &json) const
{
json["qml"] = QString(mQml.toUtf8().toBase64());
}
(mQml is a QString)
This turns the following QML:
import QtQuick 2.0
Item {
id: item
}
into this Base64 string:
aW1wb3J0IFF0UXVpY2sgMi4wCgpJdGVtIHsKICAgIGlkOiBpdGVtCn0=
As mentioned by #dtech, it's also possible to compress the byte array using qCompress() and qUncompress() to save some memory:
void SourceCodeSerialiser::read(const QJsonObject &json)
{
mQml = qUncompress(QByteArray::fromBase64(json["qml"].toString().toUtf8()));
}
void SourceCodeSerialiser::write(QJsonObject &json) const
{
json["qml"] = QString(qCompress(mQml.toUtf8(), 9).toBase64());
}
This results in the following Base64 string:
AAAAKXjay8wtyC8qUQgsCSzNTM5WMNIz4OLyLEnNVajmUgCCzBQrhUwgl6sWABKDDFM=
This is larger than the uncompressed version because the QML snippet was so small. Larger QML files will see a benefit from compression.
I am using "loadDataWithBaseUrl(...)" to load a html file, stored in assets, to Webview. that contains a string "Loading..." and a rotating GIF. String "Loading..." is hard coded, and it'll not be localized. How to replace that string dynamically, so that it can be localized?
Please help me to resolve this.
There are various solutions I could think of :
Load a different asset file according to the current language (get the current language using Locale.getDefault()), This way you can translate your HTML files independently.
Use place holders in your HTML file (for instance #loading_message#), then load the asset file in a String, replace all the occurences of the placeholder by the appropriate localised message (String.replaceAll("#loading_message#", getText(R.string.loading_message).toString())), finally load the processed HTML into the WebView using the loadData(String data, String mimeType, String encoding) function.
To load the asset file, you can do something like that:
File f = new File("file:///android_asset/my_file.html");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
StringBuffer sb = new StringBuffer();
String eachLine = br.readLine();
while(eachLine != null) {
sb.append(eachLine);
sb.append("\n");
eachLine = br.readLine();
}
// sb.toString is your HTML file as a String
I had a similar problem when using the WebView to show help text that should be translated.
My solution was to add multiple translated HTML files in assets and loading them with:
webView.loadUrl("file:///android_asset/" + getResources().getString(R.string.help_file));
For more details go to: Language specific HTML Help in Android
String str = "Loading ..."
String newStr = str.substring("Loading ".length());
newStr = context.getResourceById(R.string.loading) + newStr;
I hope the code is sufficiently clear to understand the idea: extract the string without "Loading " and concatenate it with the localized version of "Loading" string