.NET Base64解码图片及上传

/// 
    /// 图片上传 Base64解码
    /// 
    /// Base64数据
    /// 保存路径
    /// 图片名字
    /// 返回一个相对路径

    public string decodeBase64ToImage(string dataURL, string path, string imgName)
    {
        dataURL = dataURL.Replace("data:image/png;base64,", "").Replace("data:image/jgp;base64,", "").Replace("data:image/jpg;base64,", "").Replace("data:image/jpeg;base64,", "");//将base64头部信息替换
        byte[] bytes = Convert.FromBase64String(dataURL);
        MemoryStream memStream = new MemoryStream(bytes);
        Image mImage = Image.FromStream(memStream);
        Bitmap bp = new Bitmap(mImage);
        MemoryStream ms = new MemoryStream();
        string filename = path + "/" + imgName + ".jpeg";//所要保存的相对路径及名字
        string tmpRootDir = System.Web.HttpContext.Current.Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString()); //获取程序根目录 
        string imagesurl2 = tmpRootDir + filename.Replace(@"/", @"\"); //转换成绝对路径 
        bp.Save(imagesurl2, System.Drawing.Imaging.ImageFormat.Jpeg);//保存到服务器路径
        return filename;//返回相对路径                   
    }

//前台传回的json图片编码转为数组
    public string JsonToArray(string json)
    {
        JavaScriptSerializer jsS = new JavaScriptSerializer();
        JArray userArry = (JArray)JsonConvert.DeserializeObject(json);
        //获取树形用户json字符串
        string userList = userArry.ToString();
        //解析用户json信息
        JArray jar = (JArray)JsonConvert.DeserializeObject(userList);
        //lists = UpdateGroup_mem_Controls(json);
        string[] cname = new string[jar.Count];
        for (int i = 0; i < jar.Count; i++)
        {
            JObject j = JObject.Parse(jar[i].ToString());
            string name = j["name"].ToString();
            string base64 = j["base64"].ToString();
            cname[i] = decodeBase64ToImage(base64, "Image", DateTime.Now.ToFileTimeUtc().ToString());
        }

        string photoName = string.Join(",", cname);//数组转成字符串
        return photoName;
    }

 

你可能感兴趣的:(.NET Base64解码图片及上传)