我通过Ajax将Base64字符串发布到我的Web Api控制器。代码
将字符串转换为图像的代码
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;
}
}
控制器代码
public bool SaveImage(string ImgStr, string ImgName)
{
Image image = SAWHelpers.Base64ToImage(ImgStr);
String path = HttpContext.Current.Server.MapPath("~/ImageStorage"); //Path
//Check if directory exist
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path); //Create directory if it doesn't exist
}
string imageName = ImgName + ".jpg";
//set the image path
string imgPath = Path.Combine(path, imageName);
image.Save(imgPath, System.Drawing.Imaging.ImageFormat.Jpeg);
return true;
}
这总是因通用GDI +错误而失败。我错过了什么?有没有更好的方法将特定字符串保存为文件夹中的图像?
答案 0 :(得分:19)
在Base64字符串中您拥有图像的所有字节。您不需要创建Image
对象。您需要的只是从Base64解码并将此字节保存为文件。
示例强>
public bool SaveImage(string ImgStr, string ImgName)
{
String path = HttpContext.Current.Server.MapPath("~/ImageStorage"); //Path
//Check if directory exist
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path); //Create directory if it doesn't exist
}
string imageName = ImgName + ".jpg";
//set the image path
string imgPath = Path.Combine(path, imageName);
byte[] imageBytes = Convert.FromBase64String(ImgStr);
File.WriteAllBytes(imgPath, imageBytes);
return true;
}
答案 1 :(得分:0)
在ASP网络核心中,您可以从IHostingEnvironment获取路径
public YourController(IHostingEnvironment env)
{
_env = env;
}
方法,
public void SaveImage(string base64img, string outputImgFilename = "image.jpg")
{
var folderPath = System.IO.Path.Combine(_env.ContentRootPath, "imgs");
if (!System.IO.Directory.Exists(folderPath))
{
System.IO.Directory.CreateDirectory(folderPath);
}
System.IO.File.WriteAllBytes(Path.Combine(folderPath, outputImgFilename), Convert.FromBase64String(base64img));
}