Advertisement
Krubbs

GifCam Edit 1

Nov 19th, 2017
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 13.15 KB | None | 0 0
  1. using System.IO;
  2. using System.Windows;
  3. using System.Windows.Controls;
  4. using CameraControl.Core;
  5. using CameraControl.Core.Classes;
  6. using CameraControl.Core.Interfaces;
  7.  
  8. using System.Collections;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using System;
  12. using System.Drawing;
  13. using System.Drawing.Imaging;
  14. using System.Drawing.Drawing2D;
  15. using Newtonsoft.Json;
  16. using System.Diagnostics;
  17.  
  18. namespace CameraControl.Plugins.AutoExportPlugins
  19. {
  20.     public class CreateGIFPlugin : IAutoExportPlugin
  21.     {
  22.         [System.Serializable]
  23.         public class OneImage
  24.         {
  25.             public int id;
  26.             public string name;
  27.             public string path;
  28.  
  29.             public OneImage(string n, string p, int i)
  30.             {
  31.                 id = i;
  32.                 name = n;
  33.                 path = p;
  34.             }
  35.         }
  36.  
  37.         byte[] GifAnimation = { 33, 255, 11, 78, 69, 84, 83, 67, 65, 80, 69, 50, 46, 48, 3, 1, 0, 0, 0 };
  38.         byte[] Delay = { 15, 0 };
  39.  
  40.         public bool Execute(FileItem item, AutoExportPluginConfig configData)
  41.         {
  42.             configData.IsRedy = false;
  43.             configData.IsError = false;
  44.            
  45.             try
  46.             {
  47.                 CreateGifPluginViewModel conf = new CreateGifPluginViewModel(configData);
  48.  
  49.                 if (!Directory.Exists(conf.OriginalPath))
  50.                 {
  51.                     configData.IsRedy = true;
  52.                     configData.IsError = true;
  53.                     configData.Error = "[GIF Plugin] Отсутствует папка с файлами для создания GIF";
  54.                     Debug.WriteLine(configData.Error);
  55.                     return false;
  56.                 }
  57.  
  58.                 List<string> newFiles = Directory.GetFiles(conf.OriginalPath).Where(p => p.ToLower().EndsWith(".jpg") || p.ToLower().EndsWith(".jpeg")).ToList();
  59.  
  60.                 Debug.WriteLine("[GIF Plugin] Инициализация плагина GIF в папке " + conf.OriginalPath);
  61.                 Delay[0] = (byte)(255 / conf.GIFFramerate);
  62.  
  63.                 List<string> brandingFiles = new List<string>(0);
  64.  
  65.                 if (conf.UseBrand && Directory.Exists(conf.BrandingPath))
  66.                 {
  67.                     Debug.WriteLine("[GIF Plugin] Будем юзать брендирование");
  68.                     brandingFiles = Directory.GetFiles(conf.BrandingPath).Where(p => p.ToLower().EndsWith(".png")).ToList();
  69.  
  70.                     if(brandingFiles.Count == 1)
  71.                     {
  72.                         for(int i = 1; i < newFiles.Count; i++)
  73.                         {
  74.                             brandingFiles.Add(brandingFiles[0]);
  75.                         }
  76.                     }
  77.  
  78.                     else if(brandingFiles.Count != newFiles.Count && brandingFiles.Count > 0)
  79.                     {
  80.                         string onePath = brandingFiles[0];
  81.                         brandingFiles.Clear();
  82.                         for (int i = 0; i < newFiles.Count; i++)
  83.                         {
  84.                             brandingFiles.Add(onePath);
  85.                         }
  86.                     }
  87.                 }
  88.  
  89.                 if (newFiles.Count != conf.CameraCount)
  90.                 {
  91.                     configData.IsRedy = true;
  92.                     configData.IsError = true;
  93.                     configData.Error = "[GIF Plugin] В папке для создания GIF найдено всего " + newFiles.Count + " файлов, необходимо " + conf.CameraCount + ". Очистите папку вручную в случае необходимости";
  94.                     Debug.WriteLine(configData.Error);
  95.                     return false;
  96.                 }
  97.  
  98.                 char[] dc = { '_' };
  99.                 char[] dcDot = { '.' };
  100.  
  101.                 List<OneImage> imagesList = new List<OneImage>(0);
  102.                 for (int i = 0; i < newFiles.Count; i++)
  103.                 {
  104.                     int id = 0;
  105.                     string fileName = Path.GetFileNameWithoutExtension(newFiles[i]);
  106.  
  107.                     string[] decodedName = fileName.Split(dc);
  108.                     string intName = "";
  109.  
  110.                     foreach(char c in decodedName[decodedName.Length - 1].ToCharArray())
  111.                     {
  112.                         if(char.IsNumber(c))
  113.                         {
  114.                             if (c == '0')
  115.                             {
  116.                                 if (intName.Length > 0)
  117.                                     intName += c.ToString();
  118.                             }
  119.                             else
  120.                                 intName += c.ToString();
  121.                         }
  122.                     }
  123.  
  124.                     int.TryParse(intName, out id);
  125.                     Debug.WriteLine(fileName + " " + intName + " " + id);
  126.                     imagesList.Add(new OneImage(fileName + ".jpg", newFiles[i], id));
  127.                 }
  128.  
  129.                 imagesList.Sort(delegate (OneImage x, OneImage y)
  130.                 {
  131.                     return x.id.CompareTo(y.id);
  132.                 });
  133.  
  134.                 string newDirectory = conf.OriginalPath + "\\" + DateTime.Now.ToString("dd.M - hh.mm.ss");
  135.                 Debug.WriteLine("[GIF Plugin] Создание папки " + newDirectory);
  136.                 Directory.CreateDirectory(newDirectory);
  137.                 for(int i = 0; i < imagesList.Count; i++)
  138.                 {
  139.                     string newPath = newDirectory + "\\" + imagesList[i].name;
  140.                     File.Move(imagesList[i].path, newPath);
  141.                     imagesList[i].path = newPath;
  142.                 }
  143.  
  144.                 if (conf.UsePingPong)
  145.                 {
  146.                     for (int i = imagesList.Count - 2; i > 0; i--)
  147.                     {
  148.                         imagesList.Add(imagesList[i]);
  149.  
  150.                         if (brandingFiles.Count > 0)
  151.                             brandingFiles.Add(brandingFiles[i]);
  152.                     }
  153.                 }
  154.  
  155.                 string GifFile = newDirectory + "\\" + conf.FileName + ".gif";
  156.  
  157.                 MemoryStream MS = new MemoryStream();
  158.                 BinaryReader BR = new BinaryReader(MS);
  159.                 BinaryWriter BW = new BinaryWriter(new FileStream(GifFile, FileMode.Create));
  160.  
  161.                 //Rectangle rect = new Rectangle(0, 0, settings.gifWidth, settings.gifHeight);
  162.                 System.Drawing.Image cropped = new Bitmap(Resize(Crop(System.Drawing.Image.FromFile(imagesList[0].path), conf), new System.Drawing.Size(conf.GIFWidth, conf.GIFHeight)));
  163.  
  164.                 if (brandingFiles.Count > 0)
  165.                 {
  166.                     Debug.WriteLine("[GIF Plugin] Используем брендирование");
  167.  
  168.                     Graphics graphics = Graphics.FromImage(cropped);
  169.                     graphics.CompositingMode = CompositingMode.SourceOver;
  170.                     graphics.DrawImage(cropped, 0, 0);
  171.                     graphics.DrawImage(System.Drawing.Image.FromFile(brandingFiles[0]), 0, 0);
  172.                     graphics.Save();
  173.                     cropped.Save(newDirectory + "\\" + conf.FileName + conf.FileName + ".jpg");
  174.                 }
  175.  
  176.                 cropped.Save(MS, ImageFormat.Gif);
  177.                 byte[] B = MS.ToArray();
  178.                 B[10] = (byte)(B[10] & 0X78); //No global color table.
  179.                 BW.Write(B, 0, 13);
  180.                 BW.Write(GifAnimation);
  181.                 WriteGifImg(B, BW);
  182.  
  183.                 for (int i = 1; i < imagesList.Count; i++)
  184.                 {
  185.                     MS.SetLength(0);
  186.                     System.Drawing.Image or = new Bitmap(Resize(Crop(System.Drawing.Image.FromFile(imagesList[i].path), conf), new System.Drawing.Size(conf.GIFWidth, conf.GIFHeight)));
  187.  
  188.                     if (brandingFiles.Count > 0)
  189.                     {
  190.                         Graphics graphics = Graphics.FromImage(or);
  191.                         graphics.CompositingMode = CompositingMode.SourceOver;
  192.                         graphics.DrawImage(or, 0, 0);
  193.                         graphics.DrawImage(System.Drawing.Image.FromFile(brandingFiles[i]), 0, 0);
  194.                     }
  195.  
  196.                     or.Save(MS, ImageFormat.Gif);
  197.                     B = MS.ToArray();
  198.                     WriteGifImg(B, BW);
  199.                 }
  200.                 BW.Write(B[B.Length - 1]);
  201.                 BW.Close();
  202.                 MS.Dispose();
  203.  
  204.                 if (!Directory.Exists(conf.OriginalPath + "\\GIF Output"))
  205.                     Directory.CreateDirectory(conf.OriginalPath + "\\GIF Output");
  206.  
  207.                 if(File.Exists(GifFile))
  208.                 {
  209.                     List<string> gifFilesPaths = Directory.GetFiles(conf.OriginalPath + "\\GIF Output").Where(p => p.ToLower().EndsWith(".gif")).ToList();
  210.  
  211.                     string gifNewName = (gifFilesPaths.Count + 1).ToString();
  212.                     if (gifNewName.Length == 1)
  213.                         gifNewName = "00" + gifNewName;
  214.                     else if (gifNewName.Length == 2)
  215.                         gifNewName = "0" + gifNewName;
  216.  
  217.                     File.Copy(GifFile, conf.OriginalPath + "\\GIF Output\\" + gifNewName + ".gif");
  218.                 }
  219.  
  220.                 configData.IsRedy = true;
  221.                 return true;
  222.             }
  223.             catch(Exception ex)
  224.             {
  225.                 configData.IsRedy = true;
  226.                 configData.IsError = true;
  227.                 configData.Error = "[GIF Plugin] Критическая ошибка плагина GIF: " + ex;
  228.  
  229.                 Debug.WriteLine(configData.Error);
  230.  
  231.                 return false;
  232.             }
  233.         }
  234.  
  235.         public void WriteGifImg(byte[] B, BinaryWriter BW)
  236.         {
  237.             B[785] = Delay[0]; //5 secs delay
  238.             B[786] = Delay[1];
  239.             B[798] = (byte)(B[798] | 0X87);
  240.             BW.Write(B, 781, 18);
  241.             BW.Write(B, 13, 768);
  242.             BW.Write(B, 799, B.Length - 800);
  243.         }
  244.  
  245.         public System.Drawing.Image Crop(System.Drawing.Image img, CreateGifPluginViewModel conf)
  246.         {
  247.             float oldAspect = (float)img.Width / (float)img.Height;
  248.             float newAspect = (float)conf.GIFWidth / (float)conf.GIFHeight;
  249.             int newWidth = 0;
  250.             int newHeight = 0;
  251.  
  252.             if (oldAspect > newAspect)
  253.             {
  254.                 newHeight = img.Height;
  255.                 newWidth = (int)(img.Height * newAspect);
  256.  
  257.             }
  258.             else
  259.             {
  260.                 newWidth = img.Width;
  261.                 newHeight = (int)(img.Width / newAspect);
  262.             }
  263.  
  264.             int x = (img.Width - newWidth) / 2;
  265.             int y = (img.Height - newHeight) / 2;
  266.             Rectangle cropArea = new Rectangle(x, y, newWidth - 1, newHeight - 1);
  267.  
  268.             Bitmap bmpImage = new Bitmap(img);
  269.             Bitmap bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat);
  270.             return bmpCrop;
  271.         }
  272.  
  273.         public System.Drawing.Image Resize(System.Drawing.Image imgToResize, System.Drawing.Size size)
  274.         {
  275.             int sourceWidth = imgToResize.Width;
  276.             int sourceHeight = imgToResize.Height;
  277.  
  278.             float nPercent = 0;
  279.             float nPercentW = 0;
  280.             float nPercentH = 0;
  281.  
  282.             nPercentW = ((float)size.Width / (float)sourceWidth);
  283.             nPercentH = ((float)size.Height / (float)sourceHeight);
  284.  
  285.             if (nPercentH < nPercentW)
  286.                 nPercent = nPercentH;
  287.             else
  288.                 nPercent = nPercentW;
  289.  
  290.             int destWidth = (int)(sourceWidth * nPercent);
  291.             int destHeight = (int)(sourceHeight * nPercent);
  292.  
  293.             Bitmap b = new Bitmap(destWidth, destHeight);
  294.             System.Drawing.Graphics g = System.Drawing.Graphics.FromImage((System.Drawing.Image)b);
  295.             g.InterpolationMode = InterpolationMode.HighQualityBicubic;
  296.  
  297.             g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
  298.             g.Dispose();
  299.  
  300.             return (System.Drawing.Image)b;
  301.         }
  302.  
  303.         private static System.Drawing.Image PlaceImageOverImage(System.Drawing.Image background, System.Drawing.Image overlay, int x, int y, float alpha)
  304.         {
  305.             using (Graphics graphics = Graphics.FromImage(background))
  306.             {
  307.                 var cm = new ColorMatrix();
  308.                 cm.Matrix33 = alpha;
  309.  
  310.                 var ia = new ImageAttributes();
  311.                 ia.SetColorMatrix(cm);
  312.  
  313.                 graphics.DrawImage(
  314.                     overlay,
  315.                     // target
  316.                     new Rectangle(x, y, overlay.Width, overlay.Height),
  317.                     // source
  318.                     0, 0, overlay.Width, overlay.Height,
  319.                     GraphicsUnit.Pixel,
  320.                     ia);
  321.             }
  322.  
  323.             return background;
  324.         }
  325.  
  326.         public string Name
  327.         {
  328.             get { return "Create GIF"; }
  329.         }
  330.  
  331.         public UserControl GetConfig(AutoExportPluginConfig configData)
  332.         {
  333.             var cntr = new CreateGIFPluginConfig()
  334.             {
  335.                 DataContext = new CreateGifPluginViewModel(configData)
  336.             };
  337.             return cntr;
  338.         }
  339.     }
  340. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement