Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.IO;
- using System.Windows;
- using System.Windows.Controls;
- using CameraControl.Core;
- using CameraControl.Core.Classes;
- using CameraControl.Core.Interfaces;
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
- using System;
- using System.Drawing;
- using System.Drawing.Imaging;
- using System.Drawing.Drawing2D;
- using Newtonsoft.Json;
- using System.Diagnostics;
- namespace CameraControl.Plugins.AutoExportPlugins
- {
- public class CreateGIFPlugin : IAutoExportPlugin
- {
- [System.Serializable]
- public class OneImage
- {
- public int id;
- public string name;
- public string path;
- public OneImage(string n, string p, int i)
- {
- id = i;
- name = n;
- path = p;
- }
- }
- byte[] GifAnimation = { 33, 255, 11, 78, 69, 84, 83, 67, 65, 80, 69, 50, 46, 48, 3, 1, 0, 0, 0 };
- byte[] Delay = { 15, 0 };
- public bool Execute(FileItem item, AutoExportPluginConfig configData)
- {
- configData.IsRedy = false;
- configData.IsError = false;
- try
- {
- CreateGifPluginViewModel conf = new CreateGifPluginViewModel(configData);
- if (!Directory.Exists(conf.OriginalPath))
- {
- configData.IsRedy = true;
- configData.IsError = true;
- configData.Error = "[GIF Plugin] Отсутствует папка с файлами для создания GIF";
- Debug.WriteLine(configData.Error);
- return false;
- }
- List<string> newFiles = Directory.GetFiles(conf.OriginalPath).Where(p => p.ToLower().EndsWith(".jpg") || p.ToLower().EndsWith(".jpeg")).ToList();
- Debug.WriteLine("[GIF Plugin] Инициализация плагина GIF в папке " + conf.OriginalPath);
- Delay[0] = (byte)(255 / conf.GIFFramerate);
- List<string> brandingFiles = new List<string>(0);
- if (conf.UseBrand && Directory.Exists(conf.BrandingPath))
- {
- Debug.WriteLine("[GIF Plugin] Будем юзать брендирование");
- brandingFiles = Directory.GetFiles(conf.BrandingPath).Where(p => p.ToLower().EndsWith(".png")).ToList();
- if(brandingFiles.Count == 1)
- {
- for(int i = 1; i < newFiles.Count; i++)
- {
- brandingFiles.Add(brandingFiles[0]);
- }
- }
- else if(brandingFiles.Count != newFiles.Count && brandingFiles.Count > 0)
- {
- string onePath = brandingFiles[0];
- brandingFiles.Clear();
- for (int i = 0; i < newFiles.Count; i++)
- {
- brandingFiles.Add(onePath);
- }
- }
- }
- if (newFiles.Count != conf.CameraCount)
- {
- configData.IsRedy = true;
- configData.IsError = true;
- configData.Error = "[GIF Plugin] В папке для создания GIF найдено всего " + newFiles.Count + " файлов, необходимо " + conf.CameraCount + ". Очистите папку вручную в случае необходимости";
- Debug.WriteLine(configData.Error);
- return false;
- }
- char[] dc = { '_' };
- char[] dcDot = { '.' };
- List<OneImage> imagesList = new List<OneImage>(0);
- for (int i = 0; i < newFiles.Count; i++)
- {
- int id = 0;
- string fileName = Path.GetFileNameWithoutExtension(newFiles[i]);
- string[] decodedName = fileName.Split(dc);
- string intName = "";
- foreach(char c in decodedName[decodedName.Length - 1].ToCharArray())
- {
- if(char.IsNumber(c))
- {
- if (c == '0')
- {
- if (intName.Length > 0)
- intName += c.ToString();
- }
- else
- intName += c.ToString();
- }
- }
- int.TryParse(intName, out id);
- Debug.WriteLine(fileName + " " + intName + " " + id);
- imagesList.Add(new OneImage(fileName + ".jpg", newFiles[i], id));
- }
- imagesList.Sort(delegate (OneImage x, OneImage y)
- {
- return x.id.CompareTo(y.id);
- });
- string newDirectory = conf.OriginalPath + "\\" + DateTime.Now.ToString("dd.M - hh.mm.ss");
- Debug.WriteLine("[GIF Plugin] Создание папки " + newDirectory);
- Directory.CreateDirectory(newDirectory);
- for(int i = 0; i < imagesList.Count; i++)
- {
- string newPath = newDirectory + "\\" + imagesList[i].name;
- File.Move(imagesList[i].path, newPath);
- imagesList[i].path = newPath;
- }
- if (conf.UsePingPong)
- {
- for (int i = imagesList.Count - 2; i > 0; i--)
- {
- imagesList.Add(imagesList[i]);
- if (brandingFiles.Count > 0)
- brandingFiles.Add(brandingFiles[i]);
- }
- }
- string GifFile = newDirectory + "\\" + conf.FileName + ".gif";
- MemoryStream MS = new MemoryStream();
- BinaryReader BR = new BinaryReader(MS);
- BinaryWriter BW = new BinaryWriter(new FileStream(GifFile, FileMode.Create));
- //Rectangle rect = new Rectangle(0, 0, settings.gifWidth, settings.gifHeight);
- System.Drawing.Image cropped = new Bitmap(Resize(Crop(System.Drawing.Image.FromFile(imagesList[0].path), conf), new System.Drawing.Size(conf.GIFWidth, conf.GIFHeight)));
- if (brandingFiles.Count > 0)
- {
- Debug.WriteLine("[GIF Plugin] Используем брендирование");
- Graphics graphics = Graphics.FromImage(cropped);
- graphics.CompositingMode = CompositingMode.SourceOver;
- graphics.DrawImage(cropped, 0, 0);
- graphics.DrawImage(System.Drawing.Image.FromFile(brandingFiles[0]), 0, 0);
- graphics.Save();
- cropped.Save(newDirectory + "\\" + conf.FileName + conf.FileName + ".jpg");
- }
- cropped.Save(MS, ImageFormat.Gif);
- byte[] B = MS.ToArray();
- B[10] = (byte)(B[10] & 0X78); //No global color table.
- BW.Write(B, 0, 13);
- BW.Write(GifAnimation);
- WriteGifImg(B, BW);
- for (int i = 1; i < imagesList.Count; i++)
- {
- MS.SetLength(0);
- System.Drawing.Image or = new Bitmap(Resize(Crop(System.Drawing.Image.FromFile(imagesList[i].path), conf), new System.Drawing.Size(conf.GIFWidth, conf.GIFHeight)));
- if (brandingFiles.Count > 0)
- {
- Graphics graphics = Graphics.FromImage(or);
- graphics.CompositingMode = CompositingMode.SourceOver;
- graphics.DrawImage(or, 0, 0);
- graphics.DrawImage(System.Drawing.Image.FromFile(brandingFiles[i]), 0, 0);
- }
- or.Save(MS, ImageFormat.Gif);
- B = MS.ToArray();
- WriteGifImg(B, BW);
- }
- BW.Write(B[B.Length - 1]);
- BW.Close();
- MS.Dispose();
- if (!Directory.Exists(conf.OriginalPath + "\\GIF Output"))
- Directory.CreateDirectory(conf.OriginalPath + "\\GIF Output");
- if(File.Exists(GifFile))
- {
- List<string> gifFilesPaths = Directory.GetFiles(conf.OriginalPath + "\\GIF Output").Where(p => p.ToLower().EndsWith(".gif")).ToList();
- string gifNewName = (gifFilesPaths.Count + 1).ToString();
- if (gifNewName.Length == 1)
- gifNewName = "00" + gifNewName;
- else if (gifNewName.Length == 2)
- gifNewName = "0" + gifNewName;
- File.Copy(GifFile, conf.OriginalPath + "\\GIF Output\\" + gifNewName + ".gif");
- }
- configData.IsRedy = true;
- return true;
- }
- catch(Exception ex)
- {
- configData.IsRedy = true;
- configData.IsError = true;
- configData.Error = "[GIF Plugin] Критическая ошибка плагина GIF: " + ex;
- Debug.WriteLine(configData.Error);
- return false;
- }
- }
- public void WriteGifImg(byte[] B, BinaryWriter BW)
- {
- B[785] = Delay[0]; //5 secs delay
- B[786] = Delay[1];
- B[798] = (byte)(B[798] | 0X87);
- BW.Write(B, 781, 18);
- BW.Write(B, 13, 768);
- BW.Write(B, 799, B.Length - 800);
- }
- public System.Drawing.Image Crop(System.Drawing.Image img, CreateGifPluginViewModel conf)
- {
- float oldAspect = (float)img.Width / (float)img.Height;
- float newAspect = (float)conf.GIFWidth / (float)conf.GIFHeight;
- int newWidth = 0;
- int newHeight = 0;
- if (oldAspect > newAspect)
- {
- newHeight = img.Height;
- newWidth = (int)(img.Height * newAspect);
- }
- else
- {
- newWidth = img.Width;
- newHeight = (int)(img.Width / newAspect);
- }
- int x = (img.Width - newWidth) / 2;
- int y = (img.Height - newHeight) / 2;
- Rectangle cropArea = new Rectangle(x, y, newWidth - 1, newHeight - 1);
- Bitmap bmpImage = new Bitmap(img);
- Bitmap bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat);
- return bmpCrop;
- }
- public System.Drawing.Image Resize(System.Drawing.Image imgToResize, System.Drawing.Size size)
- {
- int sourceWidth = imgToResize.Width;
- int sourceHeight = imgToResize.Height;
- float nPercent = 0;
- float nPercentW = 0;
- float nPercentH = 0;
- nPercentW = ((float)size.Width / (float)sourceWidth);
- nPercentH = ((float)size.Height / (float)sourceHeight);
- if (nPercentH < nPercentW)
- nPercent = nPercentH;
- else
- nPercent = nPercentW;
- int destWidth = (int)(sourceWidth * nPercent);
- int destHeight = (int)(sourceHeight * nPercent);
- Bitmap b = new Bitmap(destWidth, destHeight);
- System.Drawing.Graphics g = System.Drawing.Graphics.FromImage((System.Drawing.Image)b);
- g.InterpolationMode = InterpolationMode.HighQualityBicubic;
- g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
- g.Dispose();
- return (System.Drawing.Image)b;
- }
- private static System.Drawing.Image PlaceImageOverImage(System.Drawing.Image background, System.Drawing.Image overlay, int x, int y, float alpha)
- {
- using (Graphics graphics = Graphics.FromImage(background))
- {
- var cm = new ColorMatrix();
- cm.Matrix33 = alpha;
- var ia = new ImageAttributes();
- ia.SetColorMatrix(cm);
- graphics.DrawImage(
- overlay,
- // target
- new Rectangle(x, y, overlay.Width, overlay.Height),
- // source
- 0, 0, overlay.Width, overlay.Height,
- GraphicsUnit.Pixel,
- ia);
- }
- return background;
- }
- public string Name
- {
- get { return "Create GIF"; }
- }
- public UserControl GetConfig(AutoExportPluginConfig configData)
- {
- var cntr = new CreateGIFPluginConfig()
- {
- DataContext = new CreateGifPluginViewModel(configData)
- };
- return cntr;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement