bool delete = true; //напишите false, если не надо удалять оригинальное фото
Random rnd = new Random();
//Случайный уровень контрастности 0т 16 до 28. Чем он выше, тем контрастнее и ярче картинка на выходе
int threshold = rnd.Next(16,28);
string d = project.Directory + @"\фото\"; //путь к директории
if(!Directory.Exists(d))
{
Directory.CreateDirectory(d);
throw new Exception("положите фотографии для обработки в папку фото");
}
string[] ld = System.IO.Directory.GetFiles(d, "*.*", System.IO.SearchOption.AllDirectories);
if(ld.Length == 0) throw new Exception("нет фото для обработки");
int sl = rnd.Next(ld.Length);
string s = ld[sl];
//using (System.Drawing.Bitmap sourceBitmap = new Bitmap(System.Drawing.Image.FromFile(s)));
Image img = System.Drawing.Image.FromFile(s);
Bitmap sourceBitmap = new Bitmap(img);
System.Drawing.Imaging.BitmapData sourceData = sourceBitmap.LockBits(new Rectangle(0, 0,
sourceBitmap.Width, sourceBitmap.Height),
System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
byte[] pixelBuffer = new byte [sourceData.Stride * sourceData.Height];
System.Runtime.InteropServices.Marshal.Copy(sourceData.Scan0, pixelBuffer, 0, pixelBuffer.Length);
sourceBitmap.UnlockBits(sourceData);
double contrastLevel = Math.Pow((100.0 + threshold) / 100.0, 2);
double blue = 0;
double green = 0;
double red = 0;
for (int k = 0; k + 4 < pixelBuffer.Length; k += 4) {
blue = ((((pixelBuffer[k] / 255.0) - 0.5) * contrastLevel) + 0.5) * 255.0;
green = ((((pixelBuffer[k + 1] / 255.0) - 0.5) * contrastLevel) + 0.5) * 255.0;
red = ((((pixelBuffer[k + 2] / 255.0) - 0.5) *
contrastLevel) + 0.5) * 255.0;
if (blue > 255)
{ blue = 255; }
else if (blue < 0)
{ blue = 0; }
if (green > 255)
{ green = 255; }
else if (green < 0)
{ green = 0; }
if (red > 255)
{ red = 255; }
else if (red < 0)
{ red = 0; }
pixelBuffer[k] = (byte)blue;
pixelBuffer[k + 1] = (byte)green;
pixelBuffer[k + 2] = (byte)red;
}
int width = sourceBitmap.Width;
int height = sourceBitmap.Height;
sourceBitmap.Dispose();
Bitmap resultBitmap = new Bitmap(width, height);
System.Drawing.Imaging.BitmapData resultData = resultBitmap.LockBits(new Rectangle(0, 0,
resultBitmap.Width, resultBitmap.Height),
System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
System.Runtime.InteropServices.Marshal.Copy(pixelBuffer, 0, resultData.Scan0, pixelBuffer.Length);
resultBitmap.UnlockBits(resultData);
string pathDir = project.Directory + @"\обработанное фото\";
if(!Directory.Exists(pathDir)) Directory.CreateDirectory(pathDir);
string pathResult = pathDir + Path.GetFileName(ld[sl]);
if(Directory.GetFiles(pathDir).ToList().Contains(pathResult)) pathResult = pathDir + Path.GetFileNameWithoutExtension(ld[sl]) + rnd.Next(10000,99999).ToString() + ".jpg";
resultBitmap.Save(pathResult, System.Drawing.Imaging.ImageFormat.Jpeg);
resultBitmap.Dispose();
img.Dispose();
if(delete) File.Delete(ld[sl]);