Convert from DataUrl to an image in C # and write a file with bytes

Hello, I have a signature like this:

enter image description here

which is encoded in DataUrl specifically with this line:

": image / png; base64, iVBORw0KGgoAAAANSUhEUgAAAZAAAADICAYAAADGFbfiAAAYlElEQVR4Xu2dC8w1R1nHQSCIgIKVGLmoiLciFwUs ... (long line)"

What I want to do is convert this DataUrl to a PNG image and save the image on the device, this is what I am doing so far:

if (newItem.FieldType == FormFieldType.Signature) { if (newItem.ItemValue != null) { //string completeImageName = Auth.host + "/" + li[i]; string path; string filename; string stringName = newItem.ItemValue; var base64Data = Regex.Match(stringName, @"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value; var binData = Convert.FromBase64String(base64Data); path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); filename = Path.Combine(path, base64Data); if (!File.Exists(filename)) { using (var stream = new MemoryStream(binData)) { //Code crashing here-------------------------- File.WriteAllBytes(filename, binData); } } newItem.ItemValue = filename; } } App.Database.SaveReportItem(newItem); 

But my code makes my application crash specifically on this line:

File.WriteAllBytes (file name, binData);

The sample that I use as a link ( Link ) uses a PictureBox, but with Xamarin there is no use of a pictureBox.

Any ideas?

+8
c # memorystream xamarin xamarin.forms
source share
1 answer

As @SLaks mentioned, I don't need a MemoryStream, the problem with my code was in the path and file name for further help, this is the working code:

 if (newItem.FieldType == FormFieldType.Signature) { if (newItem.ItemValue != null) { //string completeImageName = Auth.host + "/" + li[i]; string path; string filename; string stringName = newItem.ItemValue; var base64Data = Regex.Match(stringName, @"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value; var binData = Convert.FromBase64String(base64Data); path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); //filename = Path.Combine(path, base64Data.Replace(@"/", string.Empty)); long milliseconds = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond; string fileName = "Sn" + milliseconds.ToString() + ".PNG"; filename = Path.Combine(path, fileName); if (!File.Exists(filename)) { //using (var stream = new MemoryStream(binData)) //{ File.WriteAllBytes(filename, binData); //} } newItem.ItemValue = filename; } } App.Database.SaveReportItem(newItem); 

And the image showed:

enter image description here

+8
source share

All Articles