从DataUrl转换为C#中的Image并写入包含字节的文件

时间:2014-12-30 18:26:47

标签: c# .net xamarin memorystream xamarin.forms

你好,我有这样的签名:

enter image description here

,它特此编码为DataUrl:

“data:image / png; base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAADICAYAAADGFbfiAAAYlElEQVR4Xu2dC8w1R1nHQSCIgIKVGLmoiLciFwUs ...(长字符串)”

我想要做的是将此DataUrl转换为PNG图像,并将图像保存到设备,这是我到目前为止所做的:

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);

但是我的代码使我的应用程序特意崩溃在这一行:

File.WriteAllBytes(filename,binData);

我用作参考的样本(Link)正在使用PictureBox,但使用Xamarin则没有使用pictureBox。

任何想法?

2 个答案:

答案 0 :(得分:13)

正如@SLaks所说我不需要MemoryStream,我的代码的问题是路径和文件名以获得进一步帮助这是工作代码:

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);

图像显示:

enter image description here

答案 1 :(得分:3)

我刚刚清理了Mario的代码:

public void SaveDataUrlToFile(string dataUrl,string savePath) {
       var matchGroups= Regex.Match(dataUrl, @"data:image/(?<type>.+?),(?<data>.+)").Groups;
       var base64Data = matchGroups["data"].Value;
       var binData = Convert.FromBase64String(base64Data);
       System.IO.File.WriteAllBytes(savePath, binData);
}