【问题标题】:Send a base64 image to controller razor ASP.Net MVC4将base64图像发送到控制器剃须刀ASP.Net MVC4
【发布时间】:2014-04-02 21:10:24
【问题描述】:

我想将 base64 图像从我的视图发送到控制器 这是我的视图代码

@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{ 
    <img width="60" height="60" alt="" src="data:image/jpeg;base64,....."/>

    @Html.TextArea("resultText")
    <input type="submit" style="margin-left:40px;cursor:pointer;" id="l" value="Envoyer"/>
}

在我的控制器中,我想在参数中获取图像 这是控制器的代码

public ActionResult Index(HttpPostedFileBase imageFile)
{
   //Conversion
    if (imageFile!= null && imageFile.ContentLength > 0)
    {

        // for now just fail hard if there's any error however in a propper app I would expect a full demo.

        using (var engine = new TesseractEngine(Server.MapPath(@"./tessdata"), "eng", EngineMode.Default))
        {
            // have to load Pix via a bitmap since Pix doesn't support loading a stream.
            using (var image = new System.Drawing.Bitmap(imageFile.InputStream))
            {
                using (var pix = PixConverter.ToPix(image))
                {
                    using (var page = engine.Process(pix))
                    {
                        //meanConfidenceLabel.InnerText = String.Format("{0:P}", page.GetMeanConfidence());
                        //ViewBag.meanConfidenceLabel = String.Format("{0:P}", page.GetMeanConfidence());
                        ViewBag.resultText = page.GetText();

                    }
                }
            }
        }

    }

    return View();
}

上面的方法在参数中接受一个上传的图像,但我想要一个 base64 图像。 我试图通过传递 src 的值将其作为字符串获取,但它不起作用。

【问题讨论】:

    标签: c# image asp.net-mvc-4 razor


    【解决方案1】:

    我已经在我的控制器中添加了这段代码并且它工作了

    string imageDataParsed = imageFile.Substring(imageFile.IndexOf(',') + 1);
    byte[] imageBytes = Convert.FromBase64String(imageDataParsed);
    var imageStream = new MemoryStream(imageBytes, false);`
    

    【讨论】:

      【解决方案2】:

      我会将此视为尝试将任何其他字符串值发布到控制器操作。首先,您需要将图像数据放入表单字段中,以便将其与表单一起发布:

      <input type="hidden" name="imageData" value="data:image/jpeg;base64,....."/>
      

      然后您需要更新您的操作签名以捕获新字段:

      public ActionResult Index(string imageData)
      {
        ...
      }
      

      【讨论】:

      • 是的,我试过这样做,然后我需要将 base64 图像转换为位图,但我收到以下错误:输入不是有效的 Base-64 字符串,因为它包含非 base 64 字符 ...
      • 我在 stackoverflow 中阅读了一些主题来处理这个问题,但没有解决我的问题stackoverflow.com/questions/15114044/…
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 2021-12-20
      • 2013-02-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多