图片上传根据stream生成image

对于图片上传代码的整合

因为需要判断上传的图片的宽高是否符合尺寸,所以在最初拿到inputstream的时候,就直接获取image格式的图片

本来是想在下面的checkFile中获取的,不过直接使用System.Drawing.Image.FromStream(request.PostedFile.InputStream);的时候报错了,错误意思是说参数为空,应该是由于上面获取byte[]file的时候,关闭了stream,导致request.PostFile.InputStream也没有了,所以直接在IO中读取数据流的时候获取image格式对象

突然想起来还有个 image和bitmap之间的转换:

因为png格式的保存用的是bitmap空白处才不会填充,所以会使用到这种转换

Image originalImage = Image.FromFile(originalImagePath);
Bitmap oriImg = new Bitmap(originalImage);
public class UploadService
{    
    public bool SaveAs(UploadRequest request, out string filePath, out string errMessage)
        {
            filePath = string.Empty;

            //**************************************初始化byte长度.
            byte[] file = new Byte[request.PostedFile.ContentLength];
            //**************************************读取stream,并转换为byte类型以及获取image类型
            System.IO.Stream stream = request.PostedFile.InputStream;
            stream.Read(file, 0, request.PostedFile.ContentLength);
            Image image = System.Drawing.Image.FromStream(stream);
            stream.Close();
            //**************************************判断条件
            if(!CheckFile(request,image, file, out errMessage)){
                return false;
            }
            //**************************************设置路径
            SetFile(ref request);
            filePath = request.SavePath;
            //**************************************保存至文件路径
            var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
            fs.Write(file, 0, file.Length);
            fs.Flush();
            fs.Close();

            //**************************************获取相对路径
            filePath = GetSimplePath(filePath);
            if (string.IsNullOrEmpty(errMessage))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 判断文件的相关条件
        /// </summary>
        /// <param name="request"></param>
        /// <param name="file"></param>
        /// <param name="errMessage"></param>
        /// <returns></returns>
        private bool CheckFile(UploadRequest request,Image image, byte[] file, out string errMessage)
        {
            errMessage = string.Empty;
            // 读取原始文件名
            string localFileName = Path.GetFileName(request.PostedFile.FileName);

            //得到扩展名
            var ext = localFileName.Substring(localFileName.LastIndexOf('.') + 1).ToLower();
            //如果没有设定扩展名,则使用本身的扩展名存储
            if (string.IsNullOrEmpty(request.Ext))
            {
                request.Ext = ext;
            }
            //判断传入的数据
            if (file.Length == 0)
            {
                errMessage = "无数据提交";
                return false;
            }
            //判断文件是否超过限定大小
            if (file.Length > this.MaxFilesize)
            {
                errMessage = "文件大小超过" + this.MaxFilesize + "字节";
                return false;
            }
            //判断扩展名是否属于给定的
            if (request.Format!=null&& request.Format.Length > 0 && !request.Format.Contains(ext))
            {
                errMessage = "上传文件扩展名必需为:" + string.Join(",", request.Format);
                return false;
            }
            //判断宽高是否符合要求
            if (request.Width > 0||request.Height>0)
            {
                if (request.Width>0&&Math.Abs( image.Width-request.Width)>1)
                {
                    errMessage="宽不符合";
                    image.Dispose();
                    return false;
                }
                else if(request.Height>0&&Math.Abs(image.Height-request.Height)>1){
                    errMessage="高不符合";
                    image.Dispose();
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 设置保存路径以及创建文件夹
        /// </summary>
        /// <param name="request"></param>
        private void SetFile(ref UploadRequest request)
        {
            //如果路径没有设定,则按照给定的路径设置,不过给定路径的话,一定得先确保这个路径是正确的,且存在的
            if (string.IsNullOrEmpty(request.SavePath))
            {
                string subfolder = "day_" + DateTime.Now.ToString("yyMMdd");
                string fileFolder = Path.Combine(UploadConfigContext.UploadPath, request.Folder, subfolder);
                //文件全路径
                request.SavePath = Path.Combine(fileFolder,
                    string.Format("{0}{1}.{2}", DateTime.Now.ToString("yyyyMMddhhmmss"),
                    new Random(DateTime.Now.Millisecond).Next(10000), request.Ext)
                );
                if (!Directory.Exists(fileFolder))
                {
                    Directory.CreateDirectory(fileFolder);
                }
            }
        }
    }

    /// <summary>
    /// 上传使用的参数
    /// </summary>
    public class UploadRequest
    {
        /// <summary>
        /// 自行设置时,保存的子文件夹
        /// </summary>
        public string Folder { get; set; }
        /// <summary>
        /// 设置路径的,如果没设置,则代码自行设置
        /// </summary>
        public string SavePath { get; set; }
        /// <summary>
        /// 上传的数据
        /// </summary>
        public HttpPostedFileBase PostedFile { get; set; }
        /// <summary>
        /// 用来自定义控制扩展名的
        /// </summary>
        public string[] Format { get; set; }

        /// <summary>
        /// 控制宽,<=0则表示不管
        /// </summary>
        public int Width { get; set; }
        /// <summary>
        /// 控制高,<=0则表示不管
        /// </summary>
        public int Height { get; set; }

        /// <summary>
        /// 扩展名
        /// </summary>
        public string Ext { get; set; }
    }
图片上传代码
原文地址:https://www.cnblogs.com/danlis/p/5955826.html