Saving a base64 string as an image into a folder on server using C# and Web Api

◇◆丶佛笑我妖孽 提交于 2020-06-24 12:22:28

问题


I am posting a Base64 string via Ajax to my Web Api controller. Code below

Code for converting string to 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;
    }
}

Controller Code

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

This is always failing with a generic GDI+ error. What am I missing ? Is there a better way to save a specific string as an image on a folder ?


回答1:


In Base64 string You have all bytes of image. You don't need create Image object. All what you need is decode from Base64 and save this bytes as file.

Example

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



回答2:


In asp net core you can get the path from IHostingEnvironment

public YourController(IHostingEnvironment env)
{
   _env = env;
}

And the method,

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


来源:https://stackoverflow.com/questions/39394129/saving-a-base64-string-as-an-image-into-a-folder-on-server-using-c-sharp-and-web

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!