Azure: decoding a string in base64 containing a picture - web-services

I am developing a web-app that has to take a picture from a JSON produced by an Azure experiment.
I have the following function.
public static Image Base64ToImage(string base64String)
{
try
{
byte[] imageBytes = System.Text.Encoding.UTF8.GetBytes(base64String);//Convert.FromBase64String(base64String);
MemoryStream ms1 = new MemoryStream(imageBytes,0,imageBytes.Length);
ms1.Write(imageBytes, 0, imageBytes.Length);
Image NewImage = Image.FromStream(ms1, true);
NewImage.Save(#"C:\TESTOK.jpg");
return NewImage;
}
catch (Exception ex)
{
string appo = ex.Message.ToString() + ex.InnerException.ToString();
return null;
}
}
It receives the string produced by the Azure webservice (a codified image). When I try to create the image through the function Image.FromStream(ms1, true); it produces an exception returning the error:
"Parameter is not valid".
The input string is the following.
iVBORw0KGgoAAAANSUhEUgAAAeAAAAHgCAMAAABKCk6nAAAADFBMVEX9/v0AAAAAzQD////A95lXAAAABHRSTlP/////bShGeQAAC+xJREFUeJztnYl22yoUAIP1///cprYQm3bZRtOZ856NEFyWsZZgNfkZBM3Ptzsg70XBcBQMR8FwFAxHwXAUDEfBcLoRHEKoUq/NNBFe5Lv2NLOrSNLYTMnNfSgHmI1ktanD9CQ45Im4I7odpmkJ467dzewpUkpolNwjOBtgyIOvNHWYGwmOW0N1lF/ck6RPi43t6kQtuNHG9eO6qeAjB+/2nmxt7ArBQ34yIguOJ+JJ6Sv1PHdl0xILvXYXExhiyHhkpBPZKhIza8FD3D9UJbM+jKVamooBVvcWRyduBYDgcW9+bZtSIc9bLpJfVUOerutkfWjdOs0OsBD8tovOLQQPqZup/Di5w/SaprLMmSpzRaZeJUdmfCm7Vre+X/Aw87k4C0DwMDT0lDHKalWR53spOGY2T9d1H5LQKwOsBE9NXUpPglO5JwQX59p45syqDVXt1im6aCtuVqfoRuhYsj3AluBy4wr+E8HZgTh3kGcRW20NSaRrBbdtX8FdBRe2qinOM1+bobJQ1tsmuOzarOCFAdYjma15iq4ED3/HP2RK5wS3bo7ikThUu0onWfBWg0PSypgb0v2zp+gw1Vsc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QbHGRxncJzBcQbHG
RxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRxncJzBcQbHGRx3L2yELnclpkkAAAAASUVORK5CYII=
I have tried to decode the image from command-line:
$ base64 -d string > stringDecoded
base64: invalid input
$ base64 -d -i string > stringDecoded
$
where the parameter -i stands for --ignore-garbage: *when decoding, ignore non-alphabet characters. So, this is the issue to solve.
For Windows you can do the same thing using decb64:
> dec64 stringa.txt
So it seems clear that the problem is that my string contains non-alphanumeric characters. How can I modify my code to solve this issue?

I have understood why no one gave me an answer: there was no answer.
Some days ago the AzureML developers modified the structure of the JSON containing the image. Now it appears like this:
It could be interesting to know why it didn't work with the previous version. Nevertheless, the problem is solved!

Related

Image loading error from base64 string Qt

string text = "Some base64 string";
QByteArray bytes = QByteArray::fromBase64(text.c_str());
cover.loadFromData(bytes);
This is my code. It's work fine, when base64 string starts with "iV". But in another case (for example when it's start with "/9j/") cover returns NULL. What's the problem?

string in webclient class c# changed to uncorrect format

I call my service in wcf as you can see :
ClientRequest.Headers["Content-type"] = "application/json";
string result = ClientRequest.DownloadString(ServiceHostName + "/NajaService.svc/GetCarData/" + plaque);
var javascriptserializer = new JavaScriptSerializer();
return javascriptserializer.Deserialize<NajaResult>(result);
But the returned data is like this :
{"CarColor":"آبي سير","CarModel":"1383","CarTip":"ال ايکس","CarType":"سواري","Chassis":"83844131","Family":"####","FuelType":1,"MotorNum":"12483068683","Name":"####","NationalCode":"0000000000","Plaque":"11-426د61","PlaqueCoded":110561426,"PlaqueType":"","SystemType":"سمند","VinNo":"IRFC831V3GJ844131"}
I converted it to UTF8 byte and again convert it to utf8 string but not solved.
The encoded data is in Persian language .
I traced the request in fiddler and i found that the data is come with the correct format as you can see ,But in my code is changed
The WebRequest contains the Encoding property you can set up before downloading the service reply. Details are here: https://msdn.microsoft.com/en-us/library/system.net.webclient.encoding(v=vs.110).aspx

Ionic 2 / cordova-plugin-file File.writeFile() refuses to create binary file correctly (png image)

In summary
File.writeFile() creates a PNG file of 0 bytes when trying to write a Blob made from base64 data.
In my application, I am trying to create a file that consists of base64 data stored in the db. The rendered equivalent of the data is a small anti-aliased graph curve in black on a transparent background (never more that 300 x 320 pixels) that has previously been created and stored from a canvas element. I have independently verified that the stored base64 data is indeed correct by rendering it at one of various base64 encoders/decoders available online.
Output from "Ionic Info"
--------------------------------
Your system information:
Cordova CLI: 6.3.1
Gulp version: CLI version 3.9.1
Gulp local:
Ionic Framework Version: 2.0.0-rc.2
Ionic CLI Version: 2.1.1
Ionic App Lib Version: 2.1.1
Ionic App Scripts Version: 0.0.39
OS:
Node Version: v6.7.0
--------------------------------
The development platform is Windows 10, and I've been testing directly on a Samsung Galaxy S7 and S4 so far.
I know that the base64 data has to be converted into binary data (as a Blob) first, as File does not yet support writing base64 directly in to an image file. I found various techniques with which to do this, and the code which seems to suit my needs the most (and reflects a similar way I would have done it in java is illustrated below):
Main code from constructor:
this.platform.ready().then(() => {
this.graphDataService.getDataItem(this.job.id).then((data) =>{
console.log("getpic:");
let imgWithMeta = data.split(",")
// base64 data
let imgData = imgWithMeta[1].trim();
// content type
let imgType = imgWithMeta[0].trim().split(";")[0].split(":")[1];
console.log("imgData:",imgData);
console.log("imgMeta:",imgType);
console.log("aftergetpic:");
// this.fs is correctly set to cordova.file.externalDataDirectory
let folderpath = this.fs;
let filename = "dotd_test.png";
File.resolveLocalFilesystemUrl(this.fs).then( (dirEntry) => {
console.log("resolved dir with:", dirEntry);
this.savebase64AsImageFile(dirEntry.nativeURL,filename,imgData,imgType);
});
});
});
Helper to convert base64 to Blob:
// convert base64 to Blob
b64toBlob(b64Data, contentType, sliceSize) {
//console.log("data packet:",b64Data);
//console.log("content type:",contentType);
//console.log("slice size:",sliceSize);
let byteCharacters = atob(b64Data);
let byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
let slice = byteCharacters.slice(offset, offset + sliceSize);
let byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
let byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
console.log("size of bytearray before blobbing:", byteArrays.length);
console.log("blob content type:", contentType);
let blob = new Blob(byteArrays, {type: contentType});
// alternative way WITHOUT chunking the base64 data
// let blob = new Blob([atob(b64Data)], {type: contentType});
return blob;
}
save the image with File.writeFile()
// save the image with File.writeFile()
savebase64AsImageFile(folderpath,filename,content,contentType){
// Convert the base64 string in a Blob
let data:Blob = this.b64toBlob(content,contentType,512);
console.log("file location attempt is:",folderpath + filename);
File.writeFile(
folderpath,
filename,
data,
{replace: true}
).then(
_ => console.log("write complete")
).catch(
err => console.log("file create failed:",err);
);
}
I have tried dozens of different decoding techniques, but the effect is the same. However, if I hardcode simple text data into the writeFile() section, like so:
File.writeFile(
folderpath,
"test.txt",
"the quick brown fox jumps over the lazy dog",
{replace: true}
)
A text file IS created correctly in the expected location with the text string above in it.
However, I've noticed that whether the file is the 0 bytes PNG, or the working text file above, in both cases the ".then()" consequence clause of the File Promise never fires.
Additionally, I swapped the above method and used the Ionic 2 native Base64-To-Gallery library to create the images, which worked without a problem. However, having the images in the user's picture gallery or camera roll is not an option for me as I do not wish to risk a user's own pictures while marshalling / packing / transmitting / deleting the data-rendered images. The images should be created and managed as part of the app.
User marcus-robinson seems to have experienced a similar issue outlined here, but it was across all file types, and not just binary types as seems to be the case here. Also, the issue seems to have been closed:
https://github.com/driftyco/ionic/issues/5638
Anybody experiencing something similar, or possibly spot some error I might have caused? I've tried dozens of alternatives but none seem to work.
I had similar behaviour saving media files which worked perfectly on iOS. Nonetheless, I had the issue of 0 bytes file creation on some Android devices in release build (dev build works perfectly). After very long search, I followed the following solution
I moved the polyfills.js script tag to the top of the index.html in the ionic project before the cordova.js tag. This re-ordering somehow the issue is resolved.
So the order should look like:
<script src="build/polyfills.js"></script>
<script type="text/javascript" src="cordova.js"></script>
Works on ionic 3 and ionic 4.
The credits go to 1
I got that working with most of your code:
this.file.writeFile(this.file.cacheDirectory, "currentCached.jpeg", this.b64toBlob(src, "image/jpg", 512) ,{replace: true})
The only difference i had was:
let byteCharacters = atob(b64Data.replace(/^data:image\/(png|jpeg|jpg);base64,/, ''));
instead of your
let byteCharacters = atob(b64Data);
Note: I did not use other trimming etc. like those techniques you used in your constructor class.

error in base64 decoding in rails

I am trying to implement decode some encoded text like---
new_parsed_plain_text="QWNjZXNzIGZvciBsZXNzIHNlY3Vy5lZ CBvbg0KDQo....so on"
puts Base64.decode64(new_parsed_plain_text)
output is
Hi Debasish,
You recently changed your security settings so that your Google Account
.
..........so on
but problem is
if body.include? "Encoding: base64"
pos = body.enum_for(:scan,/base64/).map { Regexp.last_match.begin(0) }
l_pos=body.enum_for(:scan, /\/html/).map { Regexp.last_match.begin(0) }
actual_pos=pos.first.to_i
last_pos=l_pos.first.to_i-50
new_parsed_plain_text = body[actual_pos..last_pos]
puts Base64.decode64(new_parsed_plain_text)
the output is
m▒▒66W72f▒"▒W726V7W&R2▒2&VV▒GW&▒VB▒▒РРРФ▒▒FV&6▒6▒▒Х▒▒R&V6V▒Fǒ6▒▒vVB▒▒W"6V7W&▒G▒6WGF▒▒w26▒F▒B▒▒W"v▒▒v▒R66▒V▒#ЦFV&6▒6▒▒▒GW7G&▒g▒#dv▒▒▒▒6▒▒▒2▒▒▒▒▒vW"&▒FV7FVB'▒▒▒FW&▒6V7W&▒G▒Ч7F▒F&G2▒РХ▒V6R&Rv&RF▒B▒B▒2▒▒rV6▒W"f▒"▒GF6▒W"F▒'&V▒▒▒F▒▒▒W Ц66▒V▒B▒▒▒R6▒▒▒R▒▒W"66▒V▒B6fW"v▒▒'▒V▒F▒▒▒rF▒▒26▒▒vR▒W&PУƇGG3▒▒▒wwr▒v▒▒v▒R▒6▒▒▒6WGF▒▒w2▒6V7W&▒G▒▒▒W776V7W&V3▒▒F▒V▒7v▒F6▒▒▒pЧF▒2▒FR'▒v▒▒v▒R7V6▒2v▒▒▒F▒66W72▒▒W"66▒V▒B▒РТ▒F▒▒wB&V6▒v
how can solve this problem?can any one help me?

How to encode an attachment to Base64 in Jmeter?

I'm trying to encode a file to Base64 in Jmeter to test a web service using the following script:
String file = FileUtils.readFileToString(new File("${filepath}"), "UTF-8");
vars.put("file", new String(Base64.encodeBase64(file.getBytes("UTF-8"))));
This works fine for plain/text files and does not work for other file types correctly.
How could I make it work for other file types?
Jmeter has many potions to convert a variable to "Base64", below are a few options
Bean shell pre processor
BeanShell PostProcessor
BeanShell Sampler.
Below is the "bean shell" code, which used in "Bean shell pre processor" to convert variable to Base64
import org.apache.commons.codec.binary.Base64;
String emailIs= vars.get("session");
byte[] encryptedUid = Base64.encodeBase64(emailIs.getBytes());
vars.put("genStringValue",new String(encryptedUid));
Example :
Before Base64 :jdwqoeendwqqm12sdw
After Base64 :amR3cW9lZW5kd3FxbTEyc2R3
Converted using Jmeter :
Converted Using base64 site:
As Groovy is now the preferred JSR223 script language in each JMeter Sampler, Pre- & PostProcessor, Listener, Assertion, etc. this task is pretty easy.
def fileAsBase64 = new File("${filepath}").bytes.encodeBase64().toString()
vars.put("file", fileAsBase64)
Or as one liner:
vars.put("file", new File("${filepath}").bytes.encodeBase64().toString())
That's it.
Use the function ${__base64Encode(nameofthestring)} to encode the string value and ${__base64Decode(nameofthestring)} to decode the string value.
Your issue comes from the fact that you're considering binary files as text when reading them which is wrong.
Use this for reading the file:
https://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#readFileToByteArray(java.io.File)
Then encode the byte array in Base64
Try this
import org.apache.commons.codec.binary.Base64;
String forEncoding = vars.get("userName") + ":" + vars.get("passWord");
byte[] token = Base64.encodeBase64(forEncoding.getBytes());
vars.put("token", new String(token));
Alternative for this is to directly create a groovy function in User Defined Variable as
${__groovy(new File(vars.get("filepath")).bytes.encodeBase64().toString(),)}