在 C# 中从 DataUrl 转换为图像并使用字节写入文件 [英] Convert from a DataUrl to an Image in C# and write a file with the bytes
问题描述
你好,我有这样的签名:
Hello I have signature like this:
它被编码为 DataUrl,特别是这个字符串:
which is encoded to a DataUrl specifically this string:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAADICAYAAADGFbfiAAAYlElEQVR4Xu2dC8w1R1nHQSCIgIKVGLmoiLciFwUs...(长字符串)"
我想要做的是将此 DataUrl 转换为 PNG 图像,并将图像保存到设备,这就是我目前所做的:
What i want to do is Convert this DataUrl to an PNG Image, and save the image to 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 is making my application to crash specifically in this line:
File.WriteAllBytes(filename, binData);
File.WriteAllBytes(filename, binData);
我用作参考的示例(链接)使用的是PictureBox,但有Xamarin不使用图片框.
The sample I am using as reference (Link) is using a PictureBox but with Xamarin there is no use of a pictureBox.
有什么想法吗?
推荐答案
正如@SLaks 提到的,我不需要 MemoryStream,我的代码的问题是路径和文件名以获得进一步帮助,这是工作代码:
As @SLaks mentioned I didn't need a MemoryStream, the problem with my code was the path and the filename 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);
图片显示:
这篇关于在 C# 中从 DataUrl 转换为图像并使用字节写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!