.net 将base64转为图片

1、base64的格式为:

data:image/jpeg;base64,sandkansncquiueui3jk

2、ajax传输会把+转为空格

 

3、后台处理的代码:

 string imgPath = Server.MapPath("~/Img/");
            string newFileName = string.Format("{0:yyyy-MM-dd-hh-mm-ss-ffff}.jpeg", DateTime.Now);
            //base64的格式为  data:image/jpeg;base64,sandkansncquiueui3jk
            string[] imgStr = ImageBase64.Split(',');
            //ajax在传输过程中会将+变为空格
            byte[] imageBytes = Convert.FromBase64String(imgStr[1].Replace(" ", "+"));
            //将base64转为图片
            using (MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
            {
                if (!Directory.Exists(imgPath))
                {
                    Directory.CreateDirectory(imgPath);
                }
                //1方式
                System.Drawing.Bitmap bpmTemp = new System.Drawing.Bitmap(ms);
                bpmTemp.Save(Path.Combine(imgPath, newFileName));
                //2方式
                //Image image = Image.FromStream(ms);
                //image.Save(Path.Combine(imgPath, newFileName));

            }

 

参考:https://www.cnblogs.com/dh-hui/p/5387622.html

posted @ 2019-07-18 15:16  冷瞳ruin  阅读(3729)  评论(0编辑  收藏  举报