验证图片的真实类型

代码如下:

        /// <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/archive/2010/08/26/ValidateImgExtensionAndSave.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package com.ylw.p2p.common.utils; import java.awt.image.BufferedImage; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class FileUtils { public final static Map IMG_FILE_TYPE_MAP = new HashMap(); /** * @Description: 图片文件上传 * @author Xiao.Sky * @creaetime 2015年4月17日下午5:20:27 * @param request * @param response * @param photo * @param strtmp * 文件名称 xxx.jpg * @param path * 文件路径 * @param num * @return */ public static boolean updatePhoto(HttpServletRequest request,HttpServletResponse response, File photo, String strtmp,String path, long num) { File dir = new File(path); // 如果不存在就创建次文件夹 if (!dir.exists()) { dir.mkdirs(); } File newFile = new File(dir, strtmp); // 如果存在此文件就删除此文件 if (newFile.exists()) newFile.delete(); BufferedInputStream bis = null; FileInputStream fis = null; try { fis = new FileInputStream(photo); FileOutputStream fos = new FileOutputStream(newFile); BufferedImage src = ImageIO.read(fis); ImageIO.write(src, "png", fos); } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != bis) { bis.close(); } if (null != fis) { fis.close(); } } catch (IOException e) { e.printStackTrace(); } } return true; } /** * * @Description: 普通文件上传 * @author Xiao.Sky * @creaetime 2015年4月23
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值