图片检测

2018-06-18 04:31:53来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

  去年四月份在公司做了个相片检测的小工具,开始还挺懵逼的,后边就开始查资料了,记得也是在博客园上查到的一个,现在已经忘了是哪位大神说的,还是在评论区说的。给了我一个比较明确的思路,然后就开始自己弄了,虽然检测不能够100%的通过,但是还是有些收获。

  主要是检测图片格式,图片内容这两项的

  图片格式检测图片是否被修改了后缀和是否是图片,内容则是检测大小是否符合,且是否符合相片内容的,这里没有用第三方插件,完全自己想的,所以里边还是有很多错误的理解,还请多多包涵。

  这里只写上自己摸索的解决符合相片内容的思考过程及内容,首先是相片,人的上岗照片,学生证上贴的照片,都是头部和部分身体,那么必然有部分背景(幕布),如果是p的,背景色一般都是纯色,相机拍照的背景色不可能为纯色。这里写的是检测图片像素颜色的比例,随便拿一张照片来判断,颜色相同的部分所占整个图片颜色比例不能超过10%,可能5%都没有,除非背景是有p过的,对待p过的图,现在大部分都是吧,这里我没有进行判断是否是人,只是简单的判断是否符合条件(因为照片不能太小,都是几百X几百的,所以首先对图片进行了压缩,成了几十X几十的,以便进行快速计算其颜色比例)下面贴上code

public class ImgsDetectionHelper
    {
        /// <summary>
        /// 颜色值占整个图片颜色值的比例,颜色比例越高,纯度越高,检测模糊度也就越高
        /// </summary>
        public static float colorProportion = 0.2f;
        /// <summary>
        /// 检测宽度,宽度越大越精确但是消耗时间越长,推荐20~100之间
        /// </summary>
        public static int detectionWidth = 64;

        /// <summary>
        /// 检测图片规格是否符合(是否篡改了文件后缀名)
        /// </summary>
        /// <param name="imgpath">放置图片文件集合的路径</param>
        /// <param name="isFile">此路径标记的是图片地址(true)还是文件夹地址(false)</param>
        /// <returns></returns>
        public static ImageListModel DecideImageNorms(string imgpath, bool isFile)
        {
            ImageListModel imagelistmodel = new ImageListModel();
            List<string> imagesList = GetImagesList(imgpath, isFile);
            List<KeyValue> meetImageList = new List<KeyValue>();
            List<KeyValue> notmeetImageList = new List<KeyValue>();
            List<KeyValue> imageContentList = new List<KeyValue>();
            if (imagesList.Count < 1)
            {
                return null;
            }
            foreach (string imgFileName in imagesList)
            {
                KeyValue ContentEmptyPath = new KeyValue();
                using (FileStream fs = new FileStream(imgFileName, FileMode.Open, FileAccess.Read))
                {
                    if (fs.Length < 1024 * 1)
                    {
                        float lengthcontent = fs.Length / 1024;
                        ContentEmptyPath.question = "[图片大小:" + lengthcontent + "KB]不符合图片大小规格1KB,判定为图片大小不符";
                        ContentEmptyPath.path = imgFileName;
                        imageContentList.Add(ContentEmptyPath);
                        continue;
                    }
                }

                string extension = Path.GetExtension(imgFileName);
                Image img = Image.FromFile(imgFileName);
                KeyValue NoQuestionPath = new KeyValue();
                KeyValue QuestionPath = new KeyValue();
                if (img.RawFormat.Equals(ImageFormat.Jpeg))
                {
                    if (extension.ToUpper().Equals(".JPG"))
                    {
                        NoQuestionPath.question = "图片格式正常JPG";
                        NoQuestionPath.path = imgFileName;
                    }
                    else
                    {
                        //QuestionPath.question = "[本质JPG格式]格式后缀不匹配(标记格式" + extension + ")";
                        //QuestionPath.path = imgFileName;
                    }
                }
                else if (img.RawFormat.Equals(ImageFormat.Png))
                {
                    if (extension.ToUpper().Equals(".PNG"))
                    {
                        NoQuestionPath.question = "图片格式正常PNG";
                        NoQuestionPath.path = imgFileName;
                    }
                    else
                    {
                        //QuestionPath.question = "[本质PNG格式]格式后缀不匹配(标记格式" + extension + ")";
                        //QuestionPath.path = imgFileName;
                    }
                }
                else if (img.RawFormat.Equals(ImageFormat.Bmp))
                {
                    if (extension.ToUpper().Equals(".BMP"))
                    {
                        NoQuestionPath.question = "图片格式正常BMP";
                        NoQuestionPath.path = imgFileName;
                    }
                    else
                    {
                        //QuestionPath.question = "[本质PNG格式]格式后缀不匹配(标记格式" + extension + ")";
                        //QuestionPath.path = imgFileName;
                    }
                }
                //else if (img.RawFormat.Equals(ImageFormat.Gif))
                //{
                //    if (extension.ToUpper().Equals(".GIF"))
                //    {
                //        NoQuestionPath.question = "图片格式正常GIF";
                //        NoQuestionPath.path = imgFileName;
                //    }
                //    else
                //    {
                //        //QuestionPath.question = "[本质GIF格式]格式后缀不匹配(标记格式" + extension + ")";
                //        //QuestionPath.path = imgFileName;
                //    }

                //}
                else
                {
                    QuestionPath.question = "[未知格式,本质为非jpg,png,bmp格式]格式后缀不匹配(标记格式" + extension + ")";
                    QuestionPath.path = imgFileName;
                }
                if (NoQuestionPath.path != null)
                {
                    meetImageList.Add(NoQuestionPath);
                }
                if (QuestionPath.path != null)
                {
                    notmeetImageList.Add(QuestionPath);
                }
            }
            imagelistmodel.MeetList = meetImageList;
            imagelistmodel.NotMeetList = notmeetImageList;
            imagelistmodel.ImageContentEmptyList = imageContentList;
            return imagelistmodel;
        }

        /// <summary>
        /// 检测图片内部是否为纯色,这里设置整个图片最多同种颜色值所占比例大于所设置的值(colorProportion)就判定为纯色
        /// </summary>
        /// <param name="imgpath">路径</param>
        /// /// <param name="isFile">此路径标记的是图片地址(true)还是文件夹地址(false)</param>
        /// <returns></returns>
        public static ImageListModel DecideImagesContent(string imgpath, bool isFile)
        {

            ImageListModel listModel = DecideImageNorms(imgpath, isFile);
            if (listModel == null)
            {
                return null;
            }
            List<KeyValue> meetImageList = listModel.MeetList;
            if (meetImageList.Count < 1)
            {
                return listModel;
            }
            List<KeyValue> notSolidColorList = new List<KeyValue>();
            List<KeyValue> solidColorList = new List<KeyValue>();
            foreach (KeyValue imagepath in meetImageList)
            {
                KeyValue NoQuestionPath = new KeyValue();
                KeyValue QuestionPath = new KeyValue();
                Image img = Image.FromFile(imagepath.path);
                Dictionary<Color, int> colorDictionary = new Dictionary<Color, int>();
                List<Color> colorList = DetectionImgColor(img);
                for (int i = 0; i < colorList.Count; i++)
                {
                    if (colorDictionary.ContainsKey(colorList[i]))
                    {
                        continue;
                    }
                    colorDictionary.Add(colorList[i], 0);
                    for (int j = 0; j < colorList.Count; j++)
                    {
                        if (colorList[j] == colorList[i])
                            ++colorDictionary[colorList[i]];
                    }
                }
                int count = (from n in colorDictionary orderby n.Value select n.Value).Last();
                Color maxcolor = (from n in colorDictionary orderby n.Value select n.Key).Last();
                float countPersent = (float)count / (float)colorList.Count;
                if (countPersent > colorProportion)
                {
                    NoQuestionPath.question = "[目标纯度:" + colorProportion + "]判定图片为纯色,纯度:" + countPersent;
                    NoQuestionPath.path = imagepath.path;
                }
                else
                {
                    QuestionPath.question = "目标纯度:" + colorProportion + "]判定图片内容正常,纯度:" + countPersent;
                    QuestionPath.path = imagepath.path;
                }
                if (NoQuestionPath.path != null)
                {
                    solidColorList.Add(NoQuestionPath);
                }
                if (QuestionPath.path != null)
                {
                    notSolidColorList.Add(QuestionPath);
                }
            }
            listModel.SolidColorList = solidColorList;
            listModel.NotSolidColorList = notSolidColorList;
            return listModel;
        }

        /// <summary>
        /// 获取当前路径下所有符合规格的图片路径
        /// </summary>
        /// <param name="imgpath">放置图片文件集合的路径</param>
        /// /// <param name="isFile">此路径标记的是图片地址(true)还是文件夹地址(false)</param>
        /// <returns>返回符合规格的图片</returns>

        private static List<string> GetImagesList(string imgpath, bool isFile)
        {
            List<string> imgPathList = new List<string>();
            if (isFile)
            {
                string suffix = imgpath.Substring(imgpath.Length - 3);
                if (suffix.ToUpper().Equals("PNG") || suffix.ToUpper().Equals("JPG") || suffix.ToUpper().Equals("BMP"))
                {
                    imgPathList.Add(imgpath);
                    return imgPathList;
                }
                return null;
            }
            string imgtype = "*.JPG|*.BMP|*.PNG";
            string[] ImageType = imgtype.Split('|');
            for (int i = 0; i < ImageType.Length; i++)
            {
                string[] paths = Directory.GetFiles(imgpath, ImageType[i]);
                for (int j = 0; j < paths.Length; j++)
                {
                    imgPathList.Add(paths[j]);
                }
            }
            return imgPathList;
        }

        /// <summary>
        /// 获取图片像素颜色分布
        /// </summary>
        /// <param name="image">获取需要处理的图片</param>
        /// <returns></returns>
        private static List<Color> DetectionImgColor(Image image)
        {
            Bitmap myBitmap = new Bitmap(image, detectionWidth + 1, detectionWidth + 1);
            List<Color> colorlist = new List<Color>();
            for (int i = 1; i <= detectionWidth; i++)
            {
                for (int j = 1; j <= detectionWidth; j++)
                {
                    Color pixeColor = myBitmap.GetPixel(i, j);
                    colorlist.Add(pixeColor);
                }
            }
            return colorlist;
        }

        /// <summary>
        /// 图片归类集合(符合规格条件与不符合规格)
        /// </summary>
        public class ImageListModel
        {
            /// <summary>
            /// 符合图片格式的图片集合
            /// </summary>
            public List<KeyValue> MeetList { get; set; }
            /// <summary>
            /// 不符图片格式的图片集合
            /// </summary>
            public List<KeyValue> NotMeetList { get; set; }
            /// <summary>
            /// 不符合图片内容的图片集合(判定为纯色)
            /// </summary>
            public List<KeyValue> SolidColorList { get; set; }
            /// <summary>
            /// 符合图片内容的图片集合(非纯色)
            /// </summary>
            public List<KeyValue> NotSolidColorList { get; set; }
            /// <summary>
            /// 图片内容为空
            /// </summary>
            public List<KeyValue> ImageContentEmptyList { get; set; }
        }
        public class KeyValue
        {
            public string question { get; set; }
            public string path { get; set; }
        }
    }

最后,可能上边并不怎么好,还可以进行图片的颜色判断,人的皮肤和头发等因素进行更为详细的判断以便更为准确,对于人脸的五官判断还真没研究过

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:一步步开发自己的博客 .NET版(11、Web.config文件的读取和修改

下一篇:五、谈扩展方法的理解