C# 是File.writealBytes(字符串,字节[])方法可用于保存图像

C# 是File.writealBytes(字符串,字节[])方法可用于保存图像,c#,asp.net-mvc,C#,Asp.net Mvc,我正在尝试将base64映像保存到我的目录中。下面是代码。实际上,我正在我的目录中获取该文件,但当我打开它时,它会显示一个格式错误 控制器动作 public ActionResult MultiFileUploader(string[] base64image) { if (base64image.Length <= 0) return Content("Error"); for (int i = 0; i < base64image.Le

我正在尝试将base64映像保存到我的目录中。下面是代码。实际上,我正在我的目录中获取该文件,但当我打开它时,它会显示一个格式错误

控制器动作

public ActionResult MultiFileUploader(string[] base64image)
{
   if (base64image.Length <= 0)
      return Content("Error");
   for (int i = 0; i < base64image.Length; i++)
   {
      String path = Server.MapPath("~/assets/images/Test/"); //Path

      //Check if directory exist
      if (!Directory.Exists(path))
      {
         Directory.CreateDirectory(path); //Create directory if it doesn't exist
      }
      var randomFileName = Guid.NewGuid().ToString().Substring(0, 4) + ".png";
           
      //set the image path
      string imgPath = Path.Combine(path, randomFileName);
      var t = base64image[i].Substring(23);  // remove data:image/png;base64,
      byte[] data = Encoding.UTF8.GetBytes(t);
      string b64 = Convert.ToBase64String(data);
      byte[] bytes = Convert.FromBase64String(b64);
      //byte[] imageBytes = Convert.FromBase64String(ImgStr);

      System.IO.File.WriteAllBytes(imgPath, bytes);
           
   }

   string status = "error";
   try
   {                
      if (db.SaveChanges() > 0)
      {
         status = "success";
      }
   }
   catch (Exception)
   {
      throw;
   }
   return Content(status);
}
string t = base64image[i].Substring(SubChar);  // remove data:image/png;base64,
                    string t2 = t.Remove(t.Length - 1, 1);//extra quotation mark was there in end of string
                    byte[] bytes = Convert.FromBase64String(t2);
                    Image image;
                    using (MemoryStream ms = new MemoryStream(bytes))
                    {
                        image = Image.FromStream(ms);
                    }                    
                    image.Save(imgPath, ImageFormat.Png);
                    
public ActionResult多文件上传程序(字符串[]base64image)
{

如果(base64image.Length要将base64转换为二进制数据,只需调用FromBase64String。 在代码中,执行以下操作会将数据弄乱:

byte[] data = Encoding.UTF8.GetBytes(t);
b64 = Convert.ToBase64String(data);
byte[] bytes = Convert.FromBase64String(b64);
t
变量到字节数组的转换只需要
Convert.FromBase64String(t);

剥离“data:image/png;base64”时也要小心:子字符串参数是从零开始的,因此第23个字符(您需要的第一个字符)实际上有从0开始的索引22

以下是保存base64 png的方法:

    static void Main(string[] args)
    {

        var data_b64 = "data:image/png:base64,iVBORw0KGgoAAAAN..."; // your initial data

        var png_b64 = data_b64.Substring(22); // extract only base64 part.

        var png_bytes = Convert.FromBase64String(png_b64); // Convert FROM base64 To bytes

        System.IO.File.WriteAllBytes("C:\path\to\file.png", png_bytes); // save your file
    }

我修好了,谢谢你的投票,我其实是个初学者。 下面是我如何修复它的

控制器动作

public ActionResult MultiFileUploader(string[] base64image)
{
   if (base64image.Length <= 0)
      return Content("Error");
   for (int i = 0; i < base64image.Length; i++)
   {
      String path = Server.MapPath("~/assets/images/Test/"); //Path

      //Check if directory exist
      if (!Directory.Exists(path))
      {
         Directory.CreateDirectory(path); //Create directory if it doesn't exist
      }
      var randomFileName = Guid.NewGuid().ToString().Substring(0, 4) + ".png";
           
      //set the image path
      string imgPath = Path.Combine(path, randomFileName);
      var t = base64image[i].Substring(23);  // remove data:image/png;base64,
      byte[] data = Encoding.UTF8.GetBytes(t);
      string b64 = Convert.ToBase64String(data);
      byte[] bytes = Convert.FromBase64String(b64);
      //byte[] imageBytes = Convert.FromBase64String(ImgStr);

      System.IO.File.WriteAllBytes(imgPath, bytes);
           
   }

   string status = "error";
   try
   {                
      if (db.SaveChanges() > 0)
      {
         status = "success";
      }
   }
   catch (Exception)
   {
      throw;
   }
   return Content(status);
}
string t = base64image[i].Substring(SubChar);  // remove data:image/png;base64,
                    string t2 = t.Remove(t.Length - 1, 1);//extra quotation mark was there in end of string
                    byte[] bytes = Convert.FromBase64String(t2);
                    Image image;
                    using (MemoryStream ms = new MemoryStream(bytes))
                    {
                        image = Image.FromStream(ms);
                    }                    
                    image.Save(imgPath, ImageFormat.Png);
                    

您正在销毁位于
Encoding.UTF8.GetBytes(t)
writealBytes
处的图像。您应该只执行
byte[]bytes=Convert.FromBase64String(t)这可以通过以下方法解决:首先,我提取base64字符串,然后我将base64字符串转换为字节数组,然后我将字节数组转换为base64字符串,然后我将base64字符串转换为字节数组,等等……我在这里做什么……而不是盲目地删除前23个字符,找到(第一个)逗号并删除,直到出现为止(可能是“image/jpeg”?)@HansKest是的,一些真正的调试也不会有什么坏处。在调试器中很容易看到:base64image字符串最初是什么样子的,不包含我期望它包含的内容……人们应该了解如何使用调试器,而不是在某些东西不起作用时使用调试器。@GSergis感谢我修复了它,删除了编码语句directly使用了byte[]bytes=Convert.FromBase64String(t);如您所述,谢谢。