gpt4 book ai didi

c# - MVC 将 Base64 字符串转换为图像,但是...... System.FormatException

转载 作者:太空狗 更新时间:2023-10-29 20:58:59 24 4
gpt4 key购买 nike

我的 Controller 在此代码中的请求对象中获取上传的图像:

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

return fileName;
}

image 的值(至少是它的开头)看起来很像这样:

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

我尝试使用以下方法进行转换:

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

但是,这会产生 System.FormatException:“输入不是有效的 Base-64 字符串,因为它包含非 64 位字符、两个以上的填充字符或填充字符中的非法字符。”

我感觉问题在于至少字符串的开头不是 base64,但据我所知,没有一个是。我需要在解码之前解析字符串吗?我错过了完全不同的东西吗?

最佳答案

看起来您可能只能从一开始就去掉 "data:image/jpeg;base64," 部分。例如:

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
}

当然,您可能希望减少 JPEG 的特定性,但我会在第一次尝试时尝试这样做。

关于c# - MVC 将 Base64 字符串转换为图像,但是...... System.FormatException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15032622/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com