我要求用户上传图片,可以是任何图片格式。
我将base64数据传递给我的.Net控制器,以及文件名(从中我可以获得扩展名)。
然后我将该base64字符串转换为Image。
public static Image Base64ToImage(string base64String)
{
// Convert base 64 string to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
// Convert byte[] to Image
using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
{
Image image = Image.FromStream(ms, true);
return image;
}
}
我收到错误:
输入不是有效的Base-64字符串,因为它包含非基本64个字符,两个以上的填充字符或填充字符中的非法字符
我认为这是因为base54字符串有:
“data:image / jpeg; base64,/ 9j / 4AAQSkZJRgABA ....”一开始。
所以我需要修剪“data:image / jpeg; base64”,然后保存它?在删除有关文件类型的数据时,是否需要在其他位置指定它?
我发现的所有例子似乎都没有从前面修剪任何东西。他们只是保存字符串。我猜,我身边的东西是添加标题?
答案 0 :(得分:0)
嗨请查看我过去使用的工作转换器版本, 请告诉您是否需要更多解释。
似乎你转换为base64是罪魁祸首!
/// <summary>
///1 Convert String to Image
/// </summary>
/// <param name="commands"></param>
/// <returns></returns>
public Image ConvertStringtoImage(string commands)
{
byte[] photoarray = Convert.FromBase64String(commands);
MemoryStream ms = new MemoryStream(photoarray, 0, photoarray.Length);
ms.Write(photoarray, 0, photoarray.Length);
Image image = System.Drawing.Image.FromStream(ms);
return image;
}
/// <summary>
///2. Read picture from Database and return as image
/// just change the mysql to sql server type.
/// </summary>
/// <param name="commands"></param>
/// <returns></returns>
public Image Readphotofromdb(string commands)
{
Image image = null;
using (MySqlConnection dbConn = new MySqlConnection(connector))
{
using (MySqlCommand cmd = new MySqlCommand(commands, dbConn))
{
dbConn.Open();
using (MySqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
byte[] photoarray = Convert.FromBase64String(reader.GetString(0));
MemoryStream ms = new MemoryStream(photoarray, 0, photoarray.Length);
ms.Write(photoarray, 0, photoarray.Length);
image = new Bitmap(ms);
}
}
}
}
MySqlConnection.ClearAllPools();
return image;
}
/// <summary>
/// 3. Convert Image to base64 string
/// </summary>
/// <param name="image"></param>
/// <returns></returns>
public string ConvertImageToString(Image image)
{
byte[] byteArray = new byte[0];
using (MemoryStream stream = new MemoryStream())
{
image.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
stream.Close();
byteArray = stream.ToArray();
}
string base64String = Convert.ToBase64String(byteArray);
return base64String;
}
答案 1 :(得分:0)
使用类似的图像数据 /9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQ......9=代替 数据:image / jpeg; base64,/ 9j / 4AAQSkZJRgABAgAAAQABAAD / 2wBDAAgGBgcGBQgHBwcJCQgKDBQ .. .... 9 =
private void GetImage(){
string imagedata="/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQ..
....9=";
Image image=ImageFromBase64(imagedata);
}
public static Image ImageFromBase64(string base64String)
{
byte[] imageBytes = Convert.FromBase64String(base64String);
using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
{
Image image = Image.FromStream(ms, true);
return image;
}
}