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

后端 未结 2 547
你的背包
你的背包 2020-12-31 12:48

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(stri         


        
相关标签:
2条回答
  • 2020-12-31 13:30

    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));
    }
    
    0 讨论(0)
  • 2020-12-31 13:47

    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;
    }
    
    0 讨论(0)
提交回复
热议问题