将blob字符串转换为jpg文件
本文关键字:jpg 文件 转换 blob 字符串 | 更新日期: 2023-09-27 18:27:40
在我的方法中,我得到一个参数,它是表示blob文件的字符串。字符串是巨大的,这是它的开始:
"iVBORw0KGgoAAAANSUhEUgAAAHgAAAA3CAMAAADwtH5ZAAADAFBMVEX//////P///v/+///3/f3//f+zoJL3///15/SKWy
fZ3NPw///w/v78+/n++vH79vP9/f35/fz1+/n0+/T/+vj/+v3p7Ne6MgK8UgDKYBTTSxfXTTC+dWaHMBT///v4///49vf9
//7+/v77///8////9/zo2L+zTAHEZgazSQ/MgAjIqEWqUB7KdhbboELEdDm/dBfNbTG+moS5Sh/n9fbu+vD/8vH9/Pfx///
+9fr4//3//Pv4+fSSTxvGgAbOlV6bSwDKoW2wdlC6bRPLo3DElEqyPwjbcwDOpCuzNwDWgUDpdD7Un22yeln7/+71//368"
如何将其转换为.jpg文件?
字符串的base64。
string base64string = "iVBORw0KGgoAAAANSUhEUgAAAHgAAAA3CAMAAADwtH5ZAAADAFBMVEX//////P///v/+///3/f3//f+zoJL3///15/SK"; // Put the full string here
byte[] blob = Convert.FromBase64String(base64string);
File.WriteAllBytes(@"C:'Users'user'Desktop'fic.jpg", blob);
这是我在Web API中保存图像的方法。
您可以基于base64内容获得文件扩展名,并将其合并为filePath
作为
[HttpPost]
[Route("api/dashboard/saveThumbnail")]
public HttpResponseMessage SaveThumbnail()
{
//string base64string = "iVBORw0KGgoAAAANSUhEUgAAAHgAAAA3CAMAAADwtH5ZAAADAFBMVEX//////P///v/+///3/f3//f+zoJL3///15/SK";
var httpRequest = HttpContext.Current.Request;
string base64string = httpRequest["Thumbnail"]; // get from request
byte[] blob = Convert.FromBase64String(base64string);
var fileExt= GetFileExtension(base64string );
var filePath = string.Format("{0}'{1}.{2}", @"C:'Picture", "mypicture", fileExt);
File.WriteAllBytes(filePath, blob);
}
基于base64字符串获取文件类型的方法
public string GetFileExtension(string base64String)
{
var data = base64String.Substring(0, 5);
switch (data.ToUpper())
{
case "IVBOR":
return "png";
case "/9J/4":
return "jpg";
case "AAAAF":
return "mp4";
case "JVBER":
return "pdf";
case "AAABA":
return "ico";
case "UMFYI":
return "rar";
case "E1XYD":
return "rtf";
case "U1PKC":
return "txt";
case "MQOWM":
case "77U/M":
return "srt";
default:
return string.Empty;
}
}
从获取字节开始:
byte[] data = Convert.FromBase64String(theString);
当它是一个文件映像时,只需写它:
File.WriteAllBytes("test.jpg", data);