MVC Convert Base64 String to Image, but … System.FormatException

江枫思渺然 提交于 2019-12-06 01:19:00

问题


My controller is getting an uploaded image in the request object in this code:

[HttpPost]
public string Upload()
{
    string fileName = Request.Form["FileName"];
    string description = Request.Form["Description"];
    string image = Request.Form["Image"];

    return fileName;
}

The value of image (at least the beginning of it) looks a lot like this:

data:image/jpeg;base64,/9j/4AAQSkZJRgABAgEAYABgAAD/7gAOQWRvYmUAZAAAAAAB/...

I tried to convert using the following:

byte[] bImage = Convert.FromBase64String(image);

However, that gives the System.FormatException: "The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters."

I get the feeling that the problem is that at least the start of the string isn't base64, but for all I know none of it is. Do I need to parse the string before decoding it? Am I missing something completely different?


回答1:


It looks like you may just be able to strip out the "data:image/jpeg;base64," part from the start. For example:

const string ExpectedImagePrefix = "data:image/jpeg;base64,";
...
if (image.StartsWith(ExpectedImagePrefix))
{
    string base64 = image.Substring(ExpectedImagePrefix.Length);
    byte[] data = Convert.FromBase64String(base64);
    // Use the data
}
else
{
    // Not in the expected format
}

Of course you may want to make this somewhat less JPEG-specific, but I'd try that as a very first pass.




回答2:


The reason really is "data:image/jpeg;base64,", I'll suggest using this method for removing starting string from base64

var base64Content = image.Split(',')[1];
byte[] bImage = Convert.FromBase64String(base64Content);

This is Shortest solution and you don't have to use magic strings, or write a regex.



来源:https://stackoverflow.com/questions/15032622/mvc-convert-base64-string-to-image-but-system-formatexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!