1

I want to send a base64 image from my view to controller Here is my view code

@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"/>
}

And in my controller I want to get the image in argument Here is the code of the controller

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

The method above accepts an uploded image in argument but I want to have an base64 image instead. I've tried to get it as a string by passing the value of the src but It didn't work .

ItShine
  • 349
  • 1
  • 4
  • 22

2 Answers2

2

I've add this code in my controller and It worked

string imageDataParsed = imageFile.Substring(imageFile.IndexOf(',') + 1);
byte[] imageBytes = Convert.FromBase64String(imageDataParsed);
var imageStream = new MemoryStream(imageBytes, false);`
Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
ItShine
  • 349
  • 1
  • 4
  • 22
0

I would treat this the same as trying to post any other string value to a controller action. First, you need to put the image data into a form field so it will be posted with the form:

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

Then you need to update your action signature to capture the new field:

public ActionResult Index(string imageData)
{
  ...
}
Peter
  • 12,541
  • 3
  • 34
  • 39
  • Yes I've tried to do it like this , and then I need to convert the base64 image to bitmap , but I get the following error: The input is not a valid Base-64 string as it contains a non-base 64 character ... – ItShine Apr 02 '14 at 23:05
  • I've read some topic in stackoverflow that treats this issue but none resolved mine http://stackoverflow.com/questions/15114044/the-input-is-not-a-valid-base-64-string-as-it-contains-a-non-base-64-character – ItShine Apr 02 '14 at 23:13