Мой валидатор фотографий вам в помощь

мда. меня тоже этот вопрос беспокоет(((. Буду надеятся на, действительно чистые, намеренья автора. И еще я из Киева, он из Тбилиси - не конкуренты как бы)

Для всех, у кого проблемы на XP, попробуйте установить обновление .NET Framework 3.5:

For Windows XP or Vista, you will need to install .NET 3.5. Because 3.5 is an extension of .NET 2.0, the best and easiest way to install 3.5 is via the cumulative installer. This installer will install all needed prerequisites to 3.5:

http://download.microsoft.com/download/2/0/e/20e90413-712f-438c-988e-fdaa79a8ac3d/dotnetfx35.exe

1 лайк

Кстати, в любом случае - отличная идея. По крайней мере, отсечёт лишние домыслы о том, что программа делает что-либо ещё.

Кто пользовался, что скажите? Стоящая программа?

Какой вариант программы является последней версией для использования в этом году?

Пожалуйста:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.Threading;

namespace PhotoValidator
{
public partial class Form1 : Form
{
Image originalImage = null;
int?[] points = new int?[3] { null, null, null };
int pointCount = 0;

    ImageFormat imgFormat;
    int imgWidth;
    int imgHeight;
    PixelFormat imgPixelFormat;
    long imgSize;
    float imgHorizontalResolution;
    float imgVerticalResolution;
    public Form1()
    {
        InitializeComponent();
        bClear_Click(null, null);
    }
    public static Image SetMarker(Image imgPic, int height, Color color)
    {
        Bitmap bmpPic = new Bitmap(imgPic, imgPic.Width, imgPic.Height);
        using (Graphics g = Graphics.FromImage(bmpPic))
        {
            g.DrawLine(new Pen(color, 1), new Point(0, height), new Point(imgPic.Width, height));
        }
        var memStream = new MemoryStream();
        bmpPic.Save(memStream, ImageFormat.Jpeg);
        return Image.FromStream(memStream);
    }
    public static Image SetImgOpacity(Image imgPic, float imgOpac)
    {
        Bitmap bmpPic = new Bitmap(imgPic.Width, imgPic.Height);
        Graphics gfxPic = Graphics.FromImage(bmpPic);
        ColorMatrix cmxPic = new ColorMatrix();
        cmxPic.Matrix33 = imgOpac;
        ImageAttributes iaPic = new ImageAttributes();
        iaPic.SetColorMatrix(cmxPic, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
        gfxPic.DrawImage(imgPic, new Rectangle(0, 0, bmpPic.Width, bmpPic.Height), 0, 0, imgPic.Width, imgPic.Height, GraphicsUnit.Pixel, iaPic);
        gfxPic.Dispose();
        return bmpPic;
    }
    private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
    {
        if (pictureBox1.Image == null)
            return;
        if (pointCount == 3)
            return;
        if (points.Any(c => c == 600 - e.Y))
            return;
        pointCount++;
        points[pointCount - 1] = 600 - e.Y;
        pictureBox1.Image = SetMarker(pictureBox1.Image, e.Y, Color.DarkRed);
        if (pointCount == 3)
        {
            pictureBox1.Image = SetMarker(pictureBox1.Image, 600 - points.Max().Value, pTopHead.BackColor);
            pictureBox1.Image = SetMarker(pictureBox1.Image, 600 - points.Min().Value, pBottomHead.BackColor);
            pictureBox1.Image = SetMarker(pictureBox1.Image, 600 - points.Where(c => c != points.Max() && c != points.Min()).FirstOrDefault().Value, pEye.BackColor);
            lbTopHead.Text = points.Max().ToString() + "px";
            lbEye.Text = points.Where(c => c != points.Max() && c != points.Min()).FirstOrDefault().ToString() + "px";
            lbBottomHead.Text = points.Min().ToString() + "px";
        }
    }
    private void bClear_Click(object sender, EventArgs e)
    {
        gbResult.Width = 317;
        pictureBox1.Image = originalImage;
        pbResult.Image = null;
        lbEye.Text = "";
        lbBottomHead.Text = "";
        lbTopHead.Text = "";
        lbResult.ForeColor = Color.Black;
        lbResult.Text = "";
        lbInfo.Text = "";
        pointCount = 0;
        points = new int?[3] { null, null, null };
        pbIsPictureEdited.Image = Properties.Resources.question;
        pbIsPicture24Bit.Image = Properties.Resources.question;
        pbIsPictureHorizontal300dpi.Image = Properties.Resources.question;
        pbIsPictureJPG.Image = Properties.Resources.question;
        pbIsPictureLess240.Image = Properties.Resources.question;
        pbIsPictureMinimum600.Image = Properties.Resources.question;
        pbIsPictureSquare.Image = Properties.Resources.question;
        pbIsPictureVertical300dpi.Image = Properties.Resources.question;
        pbIsPicture600Scanned.Image = Properties.Resources.question;
        pbIsPicture24BitScanned.Image = Properties.Resources.question;
        pbIsPictureJPGScanned.Image = Properties.Resources.question;
        pbIsPictureLess240Scanned.Image = Properties.Resources.question;
        pbIsPictureSquareScanned.Image = Properties.Resources.question;
    }
    private void bCheck_Click(object sender, EventArgs e)
    {
        CheckPhoto(false);
    }
    private void bCheckScanned_Click(object sender, EventArgs e)
    {
        CheckPhoto(true);
    }
    private void bUpload_Click(object sender, EventArgs e)
    {
        Stream myStream = null;
        OpenFileDialog dialog = new OpenFileDialog();
        if (dialog.ShowDialog() == DialogResult.OK)
        {
            try
            {
                if ((myStream = dialog.OpenFile()) != null)
                {
                    using (myStream)
                    {
                        Image image1 = Image.FromStream(myStream);
                        Image image2 = Properties.Resources.Trans;
                        using (Graphics g = Graphics.FromImage(image1))
                        {
                            ColorMatrix matrix = new ColorMatrix();
                            matrix.Matrix33 = (float)0.2;
                            ImageAttributes attributes = new ImageAttributes();
                            attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                            g.DrawImage(image2, new Rectangle(0, 186, 600, 78), 0, 0, 600, 600, GraphicsUnit.Pixel, attributes);
                            Pen pen = new Pen(Color.DodgerBlue, 3);
                            pen.DashStyle = DashStyle.Dot;
                            g.DrawLine(pen, 299, 0, 299, 600);
                        }
                        originalImage = image1;
                        imgFormat = image1.RawFormat;
                        imgWidth = image1.Width;
                        imgHeight = image1.Height;
                        imgPixelFormat = image1.PixelFormat;
                        imgSize = myStream.Length;
                        imgHorizontalResolution = image1.HorizontalResolution;
                        imgVerticalResolution = image1.VerticalResolution;
                    }
                }
                bClear_Click(null, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка при загрузке фотографии. " + ex.Message);
            }
        }
    }
    private void CheckPhoto(bool checkForScanned)
    {
        try
        {
            gbResult.Width = 960;
            lbInfo.Text = "";
            if (pictureBox1.Image == null)
            {
                lbResult.ForeColor = Color.DarkRed;
                lbResult.Text = "Не выбрана фотография";
                return;
            }
            if (pointCount != 3)
            {
                lbResult.ForeColor = Color.DarkRed;
                lbResult.Text = "Не отмечены все три точки для проверки";
                return;
            }
            bool error = false;
            int eye = int.Parse(lbEye.Text.Replace("px", ""));
            int head = int.Parse(lbTopHead.Text.Replace("px", "")) - int.Parse(lbBottomHead.Text.Replace("px", ""));
            if (!(eye >= 336 && eye <= 414))
            {
                lbInfo.Text = string.Format("Линия глаз находится на высоте {0} пикселей, что выходит за допустимые пределы: 336px-414px", eye.ToString());
                error = true;
            }
            if (!(head >= 300 && head <= 414))
            {
                lbInfo.Text = lbInfo.Text + string.Format("{0}Размер головы {1} пикселей, что выходит за допустимые пределы: 300px-414px", lbInfo.Text.Length > 0 ? "

" : “”, head.ToString());
error = true;
}

            bool a = imgFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg);
            bool b = imgWidth == imgHeight;
            bool c = imgHeight >= 600 && imgWidth >= 600;
            bool c1 = imgHeight == 600 && imgWidth == 600;
            bool d = imgPixelFormat == PixelFormat.Format24bppRgb;
            bool f = ((double)imgSize / (double)1024) <= 240;
            bool h = (int)imgHorizontalResolution >= 300;
            bool i = (int)imgVerticalResolution >= 300;
            bool e = true;
            if (!checkForScanned)
            {
                Bitmap check = (Bitmap)originalImage;
                List<Color> colors = new List<Color>();
                for (int ii = 0; ii < check.Width; ii++)
                {
                    var color = check.GetPixel(ii, 5);
                    if (!colors.Any(gg => gg == color))
                        colors.Add(color);
                }
                if (colors.Count == 1)
                {
                    e = false;
                }
                pbIsPictureEdited.Image = e ? Properties.Resources.check : Properties.Resources.warning;
                pbIsPicture24Bit.Image = d ? Properties.Resources.check : Properties.Resources.error;
                pbIsPictureJPG.Image = a ? Properties.Resources.check : Properties.Resources.error;
                pbIsPictureLess240.Image = f ? Properties.Resources.check : Properties.Resources.error;
                pbIsPictureMinimum600.Image = c ? Properties.Resources.check : Properties.Resources.error;
                pbIsPictureSquare.Image = b ? Properties.Resources.check : Properties.Resources.error;
                pbIsPicture24BitScanned.Image = Properties.Resources.question;
                pbIsPictureJPGScanned.Image = Properties.Resources.question;
                pbIsPictureLess240Scanned.Image = Properties.Resources.question;
                pbIsPicture600Scanned.Image = Properties.Resources.question;
                pbIsPictureHorizontal300dpi.Image = Properties.Resources.question;
                pbIsPictureVertical300dpi.Image = Properties.Resources.question;
                pbIsPictureSquareScanned.Image = Properties.Resources.question;
                if (!(d && a && f && c && b))
                {
                    if (!d)
                        lbInfo.Text = lbInfo.Text + string.Format("{0}Разрешение фотографии не соответствует требуемым 24dpi", lbInfo.Text.Length > 0 ? "

" : “”);
if (!a)
lbInfo.Text = lbInfo.Text + string.Format("{0}Формат фотографии должен быть JPEG", lbInfo.Text.Length > 0 ? "
" : “”);
if (!f)
lbInfo.Text = lbInfo.Text + string.Format("{0}Размер файла {1}Kb что превышает допустимый размер в 240Kb", lbInfo.Text.Length > 0 ? "
" : “”, ((double)imgSize / (double)1024));
if (!c)
lbInfo.Text = lbInfo.Text + string.Format("{0}Размеры фотографии {1}х{2}, что не соответствует требованию к минимальному размеру 600х600", lbInfo.Text.Length > 0 ? "
" : “”, imgWidth, imgHeight);
if (!b)
lbInfo.Text = lbInfo.Text + string.Format("{0}Фотография не квадратная", lbInfo.Text.Length > 0 ? "
" : “”);
if(!e)
lbInfo.Text = lbInfo.Text + string.Format("{0}Большая вероятность, что фон на фотографии был изменен", lbInfo.Text.Length > 0 ? "
" : “”);
error = true;
}
}
else
{
pbIsPictureEdited.Image = Properties.Resources.question;
pbIsPicture24Bit.Image = Properties.Resources.question;
pbIsPictureJPG.Image = Properties.Resources.question;
pbIsPictureLess240.Image = Properties.Resources.question;
pbIsPictureMinimum600.Image = Properties.Resources.question;
pbIsPictureSquare.Image = Properties.Resources.question;

                pbIsPicture24BitScanned.Image = d ? Properties.Resources.check : Properties.Resources.error;
                pbIsPictureJPGScanned.Image = a ? Properties.Resources.check : Properties.Resources.error;
                pbIsPictureLess240Scanned.Image = f ? Properties.Resources.check : Properties.Resources.error;
                pbIsPicture600Scanned.Image = c1 ? Properties.Resources.check : Properties.Resources.error;
                pbIsPictureHorizontal300dpi.Image = h ? Properties.Resources.check : Properties.Resources.error;
                pbIsPictureVertical300dpi.Image = i ? Properties.Resources.check : Properties.Resources.error;
                pbIsPictureSquareScanned.Image = b ? Properties.Resources.check : Properties.Resources.error;
                if (!(d && a && f && c1 && b && h && i))
                {
                    if (!d)
                        lbInfo.Text = lbInfo.Text + string.Format("{0}Разрешение фотографии не соответствует требуемым 24dpi", lbInfo.Text.Length > 0 ? "

" : “”);
if (!a)
lbInfo.Text = lbInfo.Text + string.Format("{0}Формат фотографии должен быть JPEG", lbInfo.Text.Length > 0 ? "
" : “”);
if (!f)
lbInfo.Text = lbInfo.Text + string.Format("{0}Размер файла {1}Kb что превышает допустимый размер в 240Kb", lbInfo.Text.Length > 0 ? "
" : “”, ((double)imgSize / (double)1024));
if (!c1)
lbInfo.Text = lbInfo.Text + string.Format("{0}Размеры фотографии {1}x{2}, что не соответствует требованию к размеру 600х600", lbInfo.Text.Length > 0 ? "
" : “”, imgWidth, imgHeight);
if (!b)
lbInfo.Text = lbInfo.Text + string.Format("{0}Фотография не квадратная", lbInfo.Text.Length > 0 ? "
" : “”);
if (!h)
lbInfo.Text = lbInfo.Text + string.Format("{0}Горизонтальный dpi равен {1}, что не соответствует требованию к минимальному значению 300dpi", lbInfo.Text.Length > 0 ? "
" : “”, (int)imgHorizontalResolution);
if (!i)
lbInfo.Text = lbInfo.Text + string.Format("{0}Вертикальный dpi равен {1}, что не соответствует требованию к минимальному значению 300dpi", lbInfo.Text.Length > 0 ? "
" : “”, (int)imgVerticalResolution);
if (!e)
lbInfo.Text = lbInfo.Text + string.Format("{0}Большая вероятность, что фон на фотографии был изменен", lbInfo.Text.Length > 0 ? "
" : “”);

                    error = true;
                }
            }
            if (!error)
            {
                lbResult.Text = "Фотография успешно прошла проверку";
                lbResult.ForeColor = Color.DarkGreen;
                lbInfo.Text = string.Format("Линия глаз находится на высоте {0} пикселей, что вписывается в допустимые пределы: 336px-414px", eye.ToString());
                lbInfo.Text = lbInfo.Text + string.Format("

Размер головы {0} пикселей, что вписывается в допустимые пределы: 300px-414px", head.ToString());
if (!e)
{
pbResult.Image = Properties.Resources.warning;
lbInfo.Text = lbInfo.Text + string.Format("{0}Большая вероятность, что фон на фотографии был изменен", lbInfo.Text.Length > 0 ? "

" : “”);
}
else
pbResult.Image = Properties.Resources.check;
}
else
{
if (!e)
lbInfo.Text = lbInfo.Text + string.Format("{0}Большая вероятность, что фон на фотографии был изменен", lbInfo.Text.Length > 0 ? "

" : “”);

                pbResult.Image = Properties.Resources.error;
                lbResult.Text = "Фотография не прошла проверку";
                lbResult.ForeColor = Color.DarkRed;
            }
        }
        catch (Exception ex)
        {
            lbResult.Text = "Произошла ошибка";
            lbInfo.Text = ex.ToString();
        }
    }
    private void label3_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        MessageBox.Show("Автор: giond

govorimpro.us");
}

    private void Form1_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        SaveScreenShot(@"C:\Users\giond\Desktop\New folder\Results\" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg");
    }
    private void SaveScreenShot(string filename)
    {
        Bitmap bmpScreenShot = new Bitmap(this.Width, this.Height);
        Graphics gfx = Graphics.FromImage((Image)bmpScreenShot);
        gfx.CopyFromScreen(this.Left, this.Top, 0, 0, new Size(this.Width, this.Height));
        bmpScreenShot.Save(filename, ImageFormat.Jpeg);
    }
    private void exitToolStripMenuItem_Click(object sender, EventArgs e)
    {
        Application.Exit();
    }
    private void loadPictureToolStripMenuItem_Click(object sender, EventArgs e)
    {
        bUpload_Click(null, null);
    }
    private void saveScreenshotToolStripMenuItem_Click(object sender, EventArgs e)
    {
        SaveFileDialog dialog = new SaveFileDialog();
        dialog.DefaultExt = ".jpg";
        dialog.Filter = "*.jpg|";
        if (dialog.ShowDialog() == DialogResult.OK)
        {
            Thread.Sleep(1000);
            SaveScreenShot(dialog.FileName);
        }
    }
    private void viewHelpToolStripMenuItem_Click(object sender, EventArgs e)
    {
        string fbPath = Application.StartupPath;
        string fname = "help.chm";
        string filename = fbPath + @"\" + fname;
        FileInfo fi = new FileInfo(filename);
        if(fi.Exists)
            Help.ShowHelp(this, filename);
        else
            MessageBox.Show("Не имплементоровано", "Ошибка", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
    }
    private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
    {
        About a = new About();
        a.ShowDialog();
    }
}

}

4 лайка

http://www.govorimpro.us/attachments/архив-green-card-lottery-dv-2015/46493d1383232299-мой-валидатор-фотографии-вам-в-помощь-photovalidator.zip

5 лайков

Я имел в виду весь проект, чтобы его можно было скомпилировать. Так-то его и через ILSpy можно достать. Но я без претензий, конечно. Просто было бы удобно.

Не у всех есть такой каталог :slight_smile: В итоге оно крэшит по даблклику.

Шшшшшш, это не афишированная функция :slight_smile: Сделал быстро для себя, чтобы тут на форуме отвечать на вопросы пойдет ли их фото(выкладывал скриншот после проверки фотографий пользователей).

И в итоге товарищи, что делать если пишет что фон вероятно был изменен, делать другую фотку? хотя две другие с того фотоателье проходят?

Пролистайте назад. Уже писали. Не заморачиваться.

2 лайка

а вы можете еще вписать в программу проверку на резкость и отсутствие/наличие профотошопинности лица?

Возможно все, но это, поверьте, очень сложно. Там очень сложные алгоритмы, в которых я не специализируюсь; да и времени нет на это.

А как вы прокомментируете, что после изменения фото официальным кроппером, ваш валидатор постоянно пишет, что фото проверку не прошло, т.к. размер головы (от 167 до 202 рх) выходит за допустимые пределы 300х414 рх?
Уже 10 раз изменял, но меньше сделать голову не могу. Официальный сайт пишет, что фото в норме.

Вам нужно не уменьшать а увеличивать…

У меня фотография не отображается в программе. Исходник, весит 2 Мб. В чем может быть проблема?

Я смотрю как народ мучается с фото.=0 Шас в любом ФОТО -Ателье делают фото на Гринку,причем все параметры они знают. В чем дело ?Стоит это копейки.

Много…

а у меня программа ошибку выдает
Описание:
Stopped working

Сигнатура проблемы:
Имя события проблемы: CLR20r3
Сигнатура проблемы 01: photovalidator.exe
Сигнатура проблемы 02: 1.0.0.0
Сигнатура проблемы 03: 527271c0
Сигнатура проблемы 04: mscorlib
Сигнатура проблемы 05: 2.0.0.0
Сигнатура проблемы 06: 4ca2b851
Сигнатура проблемы 07: 2400
Сигнатура проблемы 08: 22
Сигнатура проблемы 09: System.IO.FileNotFoundException
Версия ОС: 6.1.7601.2.1.0.256.1
Код языка: 1049

Ознакомьтесь с заявлением о конфиденциальности в Интернете:
Заявление о конфиденциальности Windows

Если заявление о конфиденциальности в Интернете недоступно, ознакомьтесь с его локальным вариантом:
C:\Windows\system32\ru-RU\erofflps.txt

Ошибка при инициализации приложения…WinXp не работает?