将blob字符串转换为jpg文件

时间:2012-03-12 09:25:59

标签: c# image blob

在我的方法中,我得到一个参数,它是表示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。

3 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:1)

首先获取字节:

byte[] data = Convert.FromBase64String(theString);

当它是文件图像时,只需写下:

File.WriteAllBytes("test.jpg", data);

答案 2 :(得分:1)

这是将图像保存在Web API中的方法。

您可以基于64位内容获得 文件扩展名 ,并以

组合到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;
            }
        }