.NET Core Api 如何上传图片以及读取图片

在做项目中需要实现通过API上传图片,并将图片保存至服务器指定的文件夹下。

具体实现思路:

1.将图片转换为Base64数据传递给API

 //读取图片转码Base64并上传服务器
 FileStream fs = new FileStream(Imagepath, FileMode.Open);//Imagepath图片路径
 byte[] byteData = new byte[fs.Length];
 fs.Read(byteData, 0, byteData.Length);
 fs.Close();
 String data=Convert.ToBase64String(byteData);//转换Base64

2.API获取到数据后转换为图片存储到本地

/// <summary>
        /// 将Base64图片数据存入指定路径
        /// </summary>
        /// <param name="fileBase64">Base64图片数据</param>
        /// <param name="fileName">图片名</param>
        /// <param name="imagePath">保存路径</param>
        /// <returns></returns>
        public static string UploadBase64(string fileBase64, string fileName,string imagePath)
        {
            byte[] bytes = Convert.FromBase64String(fileBase64);
            var fileExtension = Path.GetExtension(fileName);
            var strDateTime = DateTime.Now.ToString("yyMMddhhmmssfff"); //取得时间字符串
            var strRan = Convert.ToString(new Random().Next(100, 999)); //生成三位随机数
            var saveName = strDateTime + strRan + fileExtension;
            //var savePath = @"./Images/" + saveName+".jpg";E:/Images/
            var savePath = imagePath + saveName + ".jpg";
            try
            {
                Image image1 = BytesToImage(bytes); //byte[]转换为图片
                System.Drawing.Bitmap image = new System.Drawing.Bitmap(image1);
                //string imgname = DateTime.Now.ToString("yyyyMMddhhmmss") + ".jpg";
                //string path = "~/images/" + imgname;
                image.Save(savePath);
                return saveName;
            }
            catch (Exception ex)
            {
                //WriteSysLog(ex.ToString(), Entity.Base_SysManage.EnumType.LogType.接口调用异常);
                return "错误";
            }

        }

3.将图片路径存到数据库,通过图片路径地址获取图片

原文

 /// <summary>
        /// 访问图片
        /// </summary>
        /// <param name="width">所访问图片的宽度,高度自动缩放,大于原图尺寸或者小于等于0返回原图</param>
        /// <param name="imgPath ">所要访问图片的名称或者相对地址</param>
        /// <returns>图片</returns>
        [HttpGet]
        public IActionResult GetImage(int width,string imgPath )
        {
            
           
            //获取图片的返回类型
            var contentTypDict = new Dictionary<string, string> {
                {"jpg","image/jpeg"},
                {"jpeg","image/jpeg"},
                {"jpe","image/jpeg"},
                {"png","image/png"},
                {"gif","image/gif"},
                {"ico","image/x-ico"},
                {"tif","image/tiff"},
                {"tiff","image/tiff"},
                {"fax","image/fax"},
                {"wbmp","image/nd.wap.wbmp"},
                {"rp","imagend.rn-realpix"}
            };
            var contentTypeStr = "image/jpeg";
            var imgTypeSplit = name.Split('.');
            var imgType = imgTypeSplit[imgTypeSplit.Length - 1].ToLower();
            //未知的图片类型
            if (!contentTypDict.ContainsKey(imgType))
            {
                imgPath = errorImage;
            }
            else
            {
                contentTypeStr = contentTypDict[imgType];
            }
            //图片不存在
            if (!new FileInfo(imgPath).Exists)
            {
                imgPath = errorImage;
            }
            //原图
            if (width <= 0)
            {
                //try
                //{
                    using (var sw = new FileStream(imgPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {
                        var bytes = new byte[sw.Length];
                        sw.Read(bytes, 0, bytes.Length);
                        sw.Close();
                        return new FileContentResult(bytes, contentTypeStr);
                    }
                //}
                //catch(Exception ex)
                //{
                   
                //}
               
            }
            //缩小图片
            using (var imgBmp = new System.Drawing.Bitmap(imgPath))
            {
                //找到新尺寸
                var oWidth = imgBmp.Width;
                var oHeight = imgBmp.Height;
                var height = oHeight;
                if (width > oWidth)
                {
                    width = oWidth;
                }
                else
                {
                    height = width * oHeight / oWidth;
                }
                var newImg = new System.Drawing.Bitmap(imgBmp, width, height);
                newImg.SetResolution(72, 72);
                var ms = new MemoryStream();
                newImg.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
                var bytes = ms.GetBuffer();
                ms.Close();
                return new FileContentResult(bytes, contentTypeStr);
            }
        }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值