验证图片的真实类型

代码如下:

        /// <summary>
        /// 验证图片的真实类型,并尝试保存图片
        /// </summary>
        /// <param name="imgStream">图片流</param>
        /// <param name="savedDirPathIsVirtual">图片被保存的目录是虚拟路径吗?true 表示是,false 表示是物理路径</param>
        /// <param name="savedDirPath">图片被保存的目录,如果不存在,则创建。如果是虚拟路径则参考的格式为“~/img/upload”。否则,参考的格式为“D:\img\upload”</param>
        /// <param name="fileNameWithoutPathAndExtension">保存的图片的文件名,不包含目录名和扩展名</param>
        /// <param name="allowFileEmpty">允许上传的文件为空吗</param>
        /// <param name="limitedImgSize_MB">限制文件的大小吗?为小于或等于零表示不限制。否则,如果限制,最大允许的大小为多少兆(M)</param>
        /// <param name="errorMessage">如果返回值为false,那么将返回的错误消息,否则,为 NULL</param>
        /// <param name="fileFullName">如果上传控件有图片,并且格式验证通过,保存成功后,输出被保存的路径。否则,为 NULL</param>
        /// <returns>验证结果,true表示成功,false表示失败</returns>
        public static bool ValidateImgExtensionAndSave(Stream imgStream, bool savedDirPathIsVirtual, string savedDirPath, string fileNameWithoutPathAndExtension, bool allowFileEmpty, double limitedImgSize_MB, out string errorMessage, out string fileFullName)
        {
            if (imgStream == null)
            {
                throw new ArgumentNullException("imgStream");
            }
            string absolutePath;
            if (savedDirPathIsVirtual)
            {
                // 虚拟路径
                absolutePath = HttpContext.Current.Server.MapPath(savedDirPath);
            }
            else
            {
                absolutePath = savedDirPath;
            }
            errorMessage = null;
            fileFullName = null;

            if (imgStream.Length == 0)
            {
                if (allowFileEmpty)
                {
                    //允许上传的文件为空
                    return true;
                }
                else
                {
                    //一定要有文件
                    errorMessage = "图片不存在,或者图片的大小为空!";
                    return false;
                }
            }

            BinaryReader r = new BinaryReader(imgStream);
            string fileclass = "";
            byte buffer;
            try
            {
                buffer = r.ReadByte();
                fileclass = buffer.ToString();
                buffer = r.ReadByte();
                fileclass += buffer.ToString();
                //r.Close();
            }
            catch (Exception)
            {
                r.Close();
                imgStream.Close();
                errorMessage = "读取图片流失败,请确定您图片的正确性!";
                return false;
            }
            //说明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar
            if (fileclass == "255216" || fileclass == "7173" || fileclass == "6677" || fileclass == "13780")
            {
                //成功
                if (limitedImgSize_MB > 0d)
                {
                    //限制图片的大小
                    double imgSize = (double)imgStream.Length / (1024 * 1024);
                    if (imgSize > limitedImgSize_MB)
                    {
                        errorMessage = "图片的大小最大不能超过 " + limitedImgSize_MB + " M(兆)";
                        imgStream.Close();
                        return false;
                    }
                }
                string imgExtension = string.Empty;
                System.Drawing.Imaging.ImageFormat imgFormat;
                switch (fileclass)
                {
                    case "255216":
                        imgExtension = ".jpg";
                        imgFormat = System.Drawing.Imaging.ImageFormat.Jpeg;
                        break;
                    case "7173":
                        imgExtension = ".gif";
                        imgFormat = System.Drawing.Imaging.ImageFormat.Gif;
                        break;
                    case "6677":
                        imgExtension = ".bmp";
                        imgFormat = System.Drawing.Imaging.ImageFormat.Bmp;
                        break;
                    case "13780":
                        imgExtension = ".png";
                        imgFormat = System.Drawing.Imaging.ImageFormat.Png;
                        break;
                    default:
                        imgFormat = System.Drawing.Imaging.ImageFormat.Jpeg;
                        break;
                }
                System.Drawing.Image img = System.Drawing.Image.FromStream(imgStream);

                if (!Directory.Exists(absolutePath))
                {
                    try
                    {
                        Directory.CreateDirectory(absolutePath);
                    }
                    catch (Exception e)
                    {
                        errorMessage = "创建用来保存图片的文件夹失败,请联系管理员!异常信息:" + e.Message;
                        return false;
                    }
                }
                string imgFullName = Path.Combine(absolutePath, fileNameWithoutPathAndExtension + imgExtension);
                img.Save(imgFullName, imgFormat);
                img.Dispose();
                imgStream.Close();
                fileFullName = Path.Combine(savedDirPath, fileNameWithoutPathAndExtension + imgExtension);
                return true;
            }
            else
            {
                errorMessage = "图片格式不正确!";
                return false;
            }
        }

        /// <summary>
        /// 验证图片的真实类型,并尝试保存图片
        /// </summary>
        /// <param name="postedFile">提交的文件信息</param>
        /// <param name="savedDirPathIsVirtual">图片被保存的目录是虚拟路径吗?true 表示是,false 表示是物理路径</param>
        /// <param name="savedDirPath">图片被保存的目录,如果不存在,则创建。如果是虚拟路径则参考的格式为“~/img/upload”。否则,参考的格式为“D:\img\upload”</param>
        /// <param name="fileNameWithoutPathAndExtension">保存的图片的文件名,不包含目录名和扩展名</param>
        /// <param name="allowFileEmpty">允许上传的文件为空吗</param>
        /// <param name="limitedImgSize_MB">限制文件的大小吗?为小于或等于零表示不限制。否则,如果限制,最大允许的大小为多少兆(M)</param>
        /// <param name="errorMessage">如果返回值为false,那么将返回的错误消息,否则,为 NULL</param>
        /// <param name="fileFullName">如果上传控件有图片,并且格式验证通过,保存成功后,输出被保存的路径。否则,为 NULL</param>
        /// <returns>验证结果,true表示成功,false表示失败</returns>
        public static bool ValidateImgExtensionAndSave(HttpPostedFileBase postedFile, bool savedDirPathIsVirtual, string savedDirPath, string fileNameWithoutPathAndExtension, bool allowFileEmpty, double limitedImgSize_MB, out string errorMessage, out string fileFullName)
        {
            if (postedFile == null)
            {
                throw new ArgumentNullException("postedFile");
            }
            return ValidateImgExtensionAndSave(postedFile.InputStream, savedDirPathIsVirtual, savedDirPath, fileNameWithoutPathAndExtension, allowFileEmpty, limitedImgSize_MB, out errorMessage, out fileFullName);
        }

        /// <summary>
        /// 验证图片的真实类型,并尝试保存图片
        /// </summary>
        /// <param name="imgContent">图片字节内容</param>
        /// <param name="savedDirPathIsVirtual">图片被保存的目录是虚拟路径吗?true 表示是,false 表示是物理路径</param>
        /// <param name="savedDirPath">图片被保存的目录,如果不存在,则创建。如果是虚拟路径则参考的格式为“~/img/upload”。否则,参考的格式为“D:\img\upload”</param>
        /// <param name="fileNameWithoutPathAndExtension">保存的图片的文件名,不包含目录名和扩展名</param>
        /// <param name="allowFileEmpty">允许上传的文件为空吗</param>
        /// <param name="limitedImgSize_MB">限制文件的大小吗?为小于或等于零表示不限制。否则,如果限制,最大允许的大小为多少兆(M)</param>
        /// <param name="errorMessage">如果返回值为false,那么将返回的错误消息,否则,为 NULL</param>
        /// <param name="fileFullName">如果上传控件有图片,并且格式验证通过,保存成功后,输出被保存的路径。否则,为 NULL</param>
        /// <returns>验证结果,true表示成功,false表示失败</returns>
        public static bool ValidateImgExtensionAndSave(byte[] imgContent, bool savedDirPathIsVirtual, string savedDirPath, string fileNameWithoutPathAndExtension, bool allowFileEmpty, double limitedImgSize_MB, out string errorMessage, out string fileFullName)
        {
            if (imgContent == null)
            {
                throw new ArgumentNullException("postedFile");
            }
            return ValidateImgExtensionAndSave(new MemoryStream(imgContent), savedDirPathIsVirtual, savedDirPath, fileNameWithoutPathAndExtension, allowFileEmpty, limitedImgSize_MB, out errorMessage, out fileFullName);
        }

谢谢浏览!

原文地址:https://www.cnblogs.com/Music/p/ValidateImgExtensionAndSave.html