C#上传图片(含有图片大小格式过滤以及改变像素安全存储)

示例一:

public JsonResult Upload(string parameter)
        {
            var file = Request.Files[0];
            try
            {
                //LogHelper.Info("文件长度:" + file.ContentLength.ToString() + "||最大照片:" + 1024 * 1024 * (Config.UploadFileSizeLimitInMB) + "||" + Config.UploadFileSizeLimitInMB);
                if (file == null || file.ContentLength == 0)
                {
                    throw new ValidationException("无上传文件");
                }
                if (file.ContentLength > 1024 * 1024 * Convert.ToInt32(uploadFileSize))
                {
                    throw new ValidationException("上传文件过大");
                }
                #region checkfile
                string fType = file.ContentType;//获取图像的类型  

                bool isimage = fType == "image/bmp" || fType == "image/gif" || fType == "image/pjpeg" || fType == "image/jpeg" || fType == "image/x-png" || fType == "image/png";

                if (fType == "application/octet-stream")
                {
                    BinaryReader reader = new BinaryReader(file.InputStream);
                    string fileClass;
                    byte buffer;
                    buffer = reader.ReadByte();
                    fileClass = buffer.ToString();
                    buffer = reader.ReadByte();
                    fileClass += buffer.ToString();
                    //reader.Close();
                    if (!(fileClass == "255216" || fileClass == "7173" || fileClass == "13780" || fileClass == "6677"))
                    //255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar 
                    {
                        throw new ValidationException("请上传图片格式的文件");
                    }
                    else
                    {
                        isimage = true;
                    }

                    file.InputStream.Position = 0;
                }

                string fext = Path.GetExtension(file.FileName).ToLower(); //获取文件后缀

                bool fextIsImage = fext == ".bmp" || fext == ".gif" || fext == ".png" || fext == ".jpeg" || fext == ".jpe" || fext == ".jpg";

                if (!(isimage && fextIsImage))
                {
                    throw new ValidationException("请上传图片格式的文件");
                }
                #endregion

                string uploadPath = string.Format("{0}\{1}", uploadFilePath, SqlTimeHelper.GetTime().ToString("yyyyMMdd"));
                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }
                var fileId = Guid.NewGuid();

                System.Drawing.Image sImage = System.Drawing.Image.FromStream(file.InputStream);
                int tw = sImage.Width - 1;
                int th = sImage.Height - 1;
                WatermarkHelper.AddWartermark(sImage);

                ImagesHelper.DrawImage(sImage, string.Format("{0}\{1}{2}", uploadPath, fileId, fext), tw, 50);

                ////原始图片的宽度和高度  
                //System.Drawing.Bitmap objPic, objNewPic;  //图像对象
                //objPic = new System.Drawing.Bitmap(sImage);
                //objNewPic = new System.Drawing.Bitmap(objPic, tw, th);  //使用指定的大小初始化objNewPic
                //objNewPic.Save(string.Format("{0}\{1}{2}", uploadPath, fileId, fext));
                //objPic.Dispose();
                //objNewPic.Dispose();
                sImage.Dispose();  //释放资源

                var rtnJson = Resource.SaveFile(file.FileName, fileId, fext);

                //下面这句代码缺少的话,上传成功后上传队列的显示不会自动消失
                return Json(new ApiSuccessResponse<FileUploadModel>(rtnJson));
            }
            catch (ValidationException ve)
            {
                return Json(new ApiInvalidParaExceptionResponse(ve.Message));
            }
            catch (Exception ue)
            {
                return Json(new ApiExceptionResponse<string>(ue));
            }
        }

示例二:

 public bool SaveStringToFile(string token, string fileName, string content)
        {
            try
            {
                string fext = Path.GetExtension(fileName).ToLower(); //获取文件后缀
                bool fextIsImage = fext == ".bmp" || fext == ".gif" || fext == ".png" || fext == ".jpeg" || fext == ".jpe" || fext == ".jpg";

                byte[] filecontent = System.Convert.FromBase64String(content);
                string path = System.Configuration.ConfigurationSettings.AppSettings["UploadFilePath"];
                BinaryReader reader = new BinaryReader(new MemoryStream(filecontent));
                string fileClass;
                byte buffer;
                buffer = reader.ReadByte();
                fileClass = buffer.ToString();
                buffer = reader.ReadByte();
                fileClass += buffer.ToString();
                reader.Close();
                bool isimage = false;
                if (!(fileClass == "255216" || fileClass == "7173" || fileClass == "13780" || fileClass == "6677"))
                //255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar 
                {
                    return false;
                }
                else
                {
                    isimage = true;
                }

                if (!(isimage && fextIsImage))
                {
                    return false;
                }
                path = Path.Combine(path, fileName);
                FileInfo info = new FileInfo(path);
                if (!Directory.Exists(info.DirectoryName))
                    Directory.CreateDirectory(info.DirectoryName);
                if (System.IO.File.Exists(path)) System.IO.File.Delete(path);
                System.IO.FileStream outfile = System.IO.File.OpenWrite(path);
                outfile.Write(filecontent, 0, filecontent.Length);
                outfile.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }