.net 5 webapi处理base64转图片(或文件txt,word,xlsx等)并保存本地

文章介绍了如何在WebAPI中替代System.Drawing.Common包,推荐使用ZKWeb.System.Drawing。提供了两个方法,分别用于Base64字符串转图片和Base64转文件,详细阐述了转换过程并给出具体代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

System.Drawing.Common仅支持Windows,webapi中无法使用。

推荐使用ZKWeb.System.Drawing。ZKWeb.System.Drawing是基于System.Drawing.Common的包。书写的代码不用变动,将引用从System.Drawing.Common改为ZKWeb.System.Drawing即可。

包:ZKWeb.System.Drawing;

引用:using System.DrawingCore;

1.Base64转图片

 public string Base64ToImage()
        {
            string imgpath = "";
            string base64String = "";//base64图片字符串
            base64String = base64String.Replace("data:image/png;base64,", "").Replace("data:image/jgp;base64,", "").Replace("data:image/jpg;base64,", "").Replace("data:image/jpeg;base64,", "");//对base64字符串进行处理,把数据头设置为空,只取数据
            byte[] imageBytes = Convert.FromBase64String(base64String);//base64字符串存数组
            MemoryStream ms = new MemoryStream(imageBytes);

            Image image = Image.FromStream(ms);//从流中加载图片
            Bitmap bp = new Bitmap(image);//创建图片对象
            imgpath = @"D:\" + DateTime.Now.ToString("yyyyMMddHHss") + ".jpg";//自己定义要存储的位置以及命名各式,此处命名格式为时间加后缀。
            bp.Save(imgpath, System.DrawingCore.Imaging.ImageFormat.Jpeg);//save(地址,图片格式)
            ms.Close();
            return imgpath;
        }

2.Base64转文件

        public string Base64ToFile([FromForm] string canshu, [FromForm] string filetype)
        {
            //DateTime time = new DateTime();
            string File = "D:\\Csharp\\test";//文件地址
            string fileName = DateTime.Now.ToString("yyyyMMddHHss") + "." + filetype;//文件名字
            string base64String = canshu;//base64文件字符串
            base64String = base64String.Trim().Substring(base64String.IndexOf(",") + 1);   //将‘,’以前的多余字符串删除
            byte[] FileBytes = Convert.FromBase64String(base64String);//base64字符串存数组
            FileStream fs = new FileStream(File + "\\" + fileName, FileMode.OpenOrCreate, FileAccess.Write);//参数一,文件地址及名称;参数二,存在则打开,不存在创建;参数三,文件写入权限
            fs.Write(FileBytes, 0, FileBytes.Length);
            fs.Close();
            return File + "\\" + fileName;
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值