-
Notifications
You must be signed in to change notification settings - Fork 2
/
GifToolForm.cs
845 lines (724 loc) · 34.5 KB
/
GifToolForm.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
using GmicFilterAnimatorApp;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Versioning;
using System.Text;
using System.Windows.Forms;
//using System.Runtime.Remoting.Messaging;
using static FileManager;
namespace GmicAnimate
{
[SupportedOSPlatform("windows")]
public partial class ToolForm : Form
{
private MainForm mainForm; // In case we need to reference the main form
public ToolForm(MainForm mainform)
{
InitializeComponent();
// Set dropdown to show the first filter and not be editable
dropdownFFmpegMode.SelectedIndex = 0;
dropdownFFmpegMode.DropDownStyle = ComboBoxStyle.DropDownList;
}
// Static variable to store the last selected folder path
private static string lastSelectedFolderPath = "";
private static int currentFramesInFolder = 0;
// Open file dialog to select GIF file
private void btnOpenFile_Click(object sender, EventArgs e)
{
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.Filter = "GIF files (*.gif)|*.gif";
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
// Get the path of specified file
var filePath = openFileDialog.FileName;
//// Read and analyze GIF file
//var gifAnalysis = AnalyzeGif(filePath);
//txtAnalysisOutput.Text = gifAnalysis;
txtGifFilePath.Text = filePath;
UpdateGifAnalysisTextbox(filePath);
}
// Else blank the textbox
else
{
txtAnalysisOutput.Text = "";
}
}
labelCrossfadeStatus.Visible = false;
}
private void UpdateGifAnalysisTextbox(string filePath)
{
if (!CheckIfFileInSystemPathOrDirectory(fileNameToCheck: "ffprobe.exe", silent: true))
{
txtAnalysisOutput.Text = "ffprobe.exe (part of ffmpeg) is required to get gif info.\r\n\r\nMake sure it is in the same directory as the application (or System PATH).";
}
else
{
// Get frame count using ffprobe
txtAnalysisOutput.Text = "Analyzing GIF file...";
int frameCount = FFProbeGetGifFrameCount(filePath);
double durationSeconds = FFProbeGetGifDurationInSeconds(filePath);
string fileName = Path.GetFileName(filePath);
txtAnalysisOutput.Text = $"File Name: {fileName}\r\n\r\nFrame Count: {frameCount}\r\nDuration: {durationSeconds:F3} seconds";
// Set new max duration for cross fade numeric up down
nudFadeDurationSeconds.Maximum = (decimal)durationSeconds;
}
labelCrossfadeStatus.Visible = false;
}
// Open folder dialogue to select folder with frames in it
private void btnOpenFolder_Click(object sender, EventArgs e)
{
using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog())
{
folderBrowserDialog.Description = "Select the folder containing the frames";
folderBrowserDialog.ShowNewFolderButton = false;
if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
{
// Get the path of specified folder
var folderPath = folderBrowserDialog.SelectedPath;
// Read and analyze frames in folder
txtFramesFolderPath.Text = folderPath;
}
}
}
// Analyze GIF with ffprobe - count number of frames with:
// ffprobe -v error -select_streams v:0 -count_frames -show_entries stream=nb_read_frames -print_format default=nokey=1:noprint_wrappers=1 input.gif
public static int FFProbeGetGifFrameCount(string filePath)
{
// Construct the command to execute
string command = "ffprobe";
string args = $"-v error -select_streams v:0 -count_frames -show_entries stream=nb_read_frames -print_format default=nokey=1:noprint_wrappers=1 \"{filePath}\"";
// Set up the process with the ProcessStartInfo class
ProcessStartInfo procStartInfo = new ProcessStartInfo(command, args)
{
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
// Start the process with the info specified and capture the output
using (Process proc = new Process())
{
proc.StartInfo = procStartInfo;
proc.Start();
// Read the output stream first and then wait.
string result = proc.StandardOutput.ReadToEnd();
proc.WaitForExit();
// Parse the result as integer. Assuming ffprobe returns a valid integer as string.
if (int.TryParse(result.Trim(), out int frameCount))
{
return frameCount;
}
else
{
throw new Exception("Failed to parse the frame count from ffprobe output.");
}
}
}
public static double FFProbeGetGifDurationInSeconds(string filePath)
{
// If it's not a gif file, return 0
if (Path.GetExtension(filePath) != ".gif")
{
return 0;
}
// Construct the command to execute
string command = "ffprobe";
string args = $"-v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 \"{filePath}\"";
// Set up the process with the ProcessStartInfo class
ProcessStartInfo procStartInfo = new ProcessStartInfo(command, args)
{
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
// Start the process with the info specified and capture the output
using (Process proc = new Process())
{
proc.StartInfo = procStartInfo;
proc.Start();
// Read the output stream first and then wait.
string result = proc.StandardOutput.ReadToEnd();
proc.WaitForExit();
// Parse the result as double
if (double.TryParse(result.Trim(), out double durationInSeconds))
{
return durationInSeconds;
}
else
{
throw new Exception("Failed to parse the duration from ffprobe output.");
}
}
}
private void ApplyCrossfadeEffect(string inputFilePath, double fadeDurationSeconds)
{
double fadeDurationHalf = fadeDurationSeconds / 2;
double totalGifDuration = FFProbeGetGifDurationInSeconds(inputFilePath);
double totalMinusTwoDuration = totalGifDuration - (2 * fadeDurationHalf); // Used to calculate the overlay start time
// Decide on file name, add _fade but must not overwrite
int count = 2;
string outputFilePath = inputFilePath.Replace(".gif", "_fade.gif");
while (File.Exists(outputFilePath))
{
outputFilePath = inputFilePath.Replace(".gif", $"_fade_{count}.gif");
count++;
}
string ffmpegCommand = "ffmpeg";
string args = $"-i \"{inputFilePath}\" -filter_complex \"[0]split[body][pre]; [pre]trim=duration={fadeDurationHalf},format=yuva420p,fade=d={fadeDurationHalf}:alpha=1,setpts=PTS+({totalMinusTwoDuration}/TB)[jt]; [body]trim={fadeDurationHalf},setpts=PTS-STARTPTS[main]; [main][jt]overlay\" -loop 0 \"{outputFilePath}\"";
ProcessStartInfo procStartInfo = new ProcessStartInfo(ffmpegCommand, args)
{
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
using (Process proc = new Process { StartInfo = procStartInfo })
{
proc.Start();
proc.WaitForExit();
}
// Check if the output file was created
if (File.Exists(outputFilePath))
{
// Get just the file name
outputFilePath = Path.GetFileName(outputFilePath);
// Update the label
labelCrossfadeStatus.Visible = true;
labelCrossfadeStatus.ForeColor = Color.Green;
labelCrossfadeStatus.Text = $"Crossfade applied. Output: {outputFilePath}";
}
else
{
//MessageBox.Show("Error applying crossfade effect.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
labelCrossfadeStatus.Visible = true;
labelCrossfadeStatus.ForeColor = Color.Red;
labelCrossfadeStatus.Text = "Error applying crossfade effect.";
}
}
public static string AnalyzeGif(string filePath)
{
if (!File.Exists(filePath))
{
return "File not found: " + filePath;
}
byte[] fileBytes = File.ReadAllBytes(filePath);
StringBuilder output = new StringBuilder();
string signature = Encoding.ASCII.GetString(fileBytes, 0, 3);
string version = Encoding.ASCII.GetString(fileBytes, 3, 3);
if (signature != "GIF")
{
return "Invalid GIF file.";
}
output.AppendLine("\n---------------------------------------------------------------------");
output.AppendLine("Reading GIF file: " + filePath);
output.AppendLine("GIF Version: " + version);
int index = 6; // Starting after the GIF header
int frameCount = 0;
int totalDurationMs = 0;
double framesPerSecond = 0;
List<int> frameDurations = new List<int>();
while (index < fileBytes.Length)
{
byte blockMarker = fileBytes[index];
if (blockMarker == 0x3B) // Trailer ';' indicating the end of the GIF file
{
break;
}
else if (blockMarker == 0x21 && fileBytes[index + 1] == 0xF9) // Graphic Control Extension
{
frameCount++;
int delay = BitConverter.ToUInt16(fileBytes, index + 4);
int frameDelayMs = delay * 10; // Convert to milliseconds
totalDurationMs += frameDelayMs;
frameDurations.Add(frameDelayMs);
index += 8; // Skip over the GCE block
}
else if (blockMarker == 0x2C) // Start of an image block
{
index += 10; // Skip the image descriptor
index++; // Skip the LZW minimum code size byte
// Skip image data sub-blocks
while (fileBytes[index] != 0)
{
index += fileBytes[index] + 1;
}
index++; // Skip the block terminator
}
else
{
index++; // Fallback to prevent infinite loops
}
}
// Calculate frames per second
if (totalDurationMs > 0 && frameCount > 0)
{
framesPerSecond = (double)frameCount / (totalDurationMs / 1000.0);
}
output.AppendLine("------------------------------------------------");
output.AppendLine($"Number of Frames: {frameCount}");
output.AppendLine($"Total Animation Duration: {totalDurationMs} ms");
output.AppendLine($"Average Frames Per Second: {framesPerSecond:0.000}"); // Truncate to 3 decimal places
// Group by frame duration
if (frameDurations.Count > 0)
{
int currentDuration = frameDurations[0];
int startFrame = 1;
int endFrame = 1;
for (int i = 1; i < frameDurations.Count; i++)
{
if (frameDurations[i] == currentDuration)
{
endFrame++;
}
else
{
if (startFrame == endFrame)
{
output.AppendLine($"Frame {startFrame} Duration: {currentDuration} ms");
}
else
{
output.AppendLine($"Frames {startFrame}-{endFrame} Duration: {currentDuration} ms");
}
startFrame = i + 1;
endFrame = i + 1;
currentDuration = frameDurations[i];
}
}
// Handle the last sequence
if (startFrame == endFrame)
{
output.AppendLine($"Frame {startFrame} Duration: {currentDuration} ms");
}
else
{
output.AppendLine($"Frames {startFrame}-{endFrame} Duration: {currentDuration} ms");
}
}
output.AppendLine("---------------------------------------------------------------------\n");
return output.ToString();
}
private void txtGifFilePath_TextChanged(object sender, EventArgs e)
{
string trimmedPath = txtGifFilePath.Text.Trim('"').Trim('\'');
// Update the box to not include quotes disable the textChanged handler while doing this to prevent infinite loop
txtGifFilePath.TextChanged -= txtGifFilePath_TextChanged;
txtGifFilePath.Text = trimmedPath;
txtGifFilePath.TextChanged += txtGifFilePath_TextChanged;
// Check validity of filepath
if (!File.Exists(trimmedPath))
{
txtAnalysisOutput.Text = "File not found.";
buttonAddCrossfade.Enabled = false;
btnCheckAlpha.Visible = false;
return;
}
else if (Path.GetExtension(trimmedPath) != ".gif")
{
txtAnalysisOutput.Text = "Analysis is for GIF files only.";
// Disable the crossfade button if the file is not a gif
buttonAddCrossfade.Enabled = false;
// Enable alpha check button if the file is not a gif
btnCheckAlpha.Visible = true;
return;
}
else
{
buttonAddCrossfade.Enabled = true;
btnCheckAlpha.Visible = false;
UpdateGifAnalysisTextbox(trimmedPath);
}
}
// Checks for file in system path or current directory
private bool CheckIfFileInSystemPathOrDirectory(string fileNameToCheck, bool silent)
{
string pathCheckResult = Environment.GetEnvironmentVariable("PATH")
.Split(';')
.Where(s => File.Exists(Path.Combine(s, fileNameToCheck)))
.FirstOrDefault();
bool currentDirectoryCheck = File.Exists(fileNameToCheck);
bool fullResult = currentDirectoryCheck || pathCheckResult != null;
if (!fullResult && !silent)
{
MessageBox.Show(fileNameToCheck + " not found. Please make sure it is in the same directory as the application (or System PATH).", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return fullResult;
}
private void checkBoxUseSameOutputDir_CheckedChanged(object sender, EventArgs e)
{
}
private void buttonOpenFolder_Click(object sender, EventArgs e)
{
txtFramesFolderPath.Text = FolderSelector(tryLastSelection: true);
}
private string FolderSelector(bool tryLastSelection = true)
{
var folderOpenDialogue = new FolderPicker();
// Check if the lastSelectedFolderPath is not empty and valid
if (!string.IsNullOrEmpty(lastSelectedFolderPath) && tryLastSelection)
{
try
{
DirectoryInfo directoryInfo = new DirectoryInfo(lastSelectedFolderPath);
DirectoryInfo parentDir = directoryInfo.Parent;
// If parent directory exists, set it as the initial input path
if (parentDir != null)
{
folderOpenDialogue.InputPath = parentDir.FullName;
}
else
{
// If no parent, use the current last selected path
folderOpenDialogue.InputPath = lastSelectedFolderPath;
}
}
catch (Exception)
{
// In case of an exception (e.g., path does not exist), fallback to current directory
folderOpenDialogue.InputPath = Directory.GetCurrentDirectory();
}
}
else
{
// Default to current directory if no folder has been selected before
folderOpenDialogue.InputPath = Directory.GetCurrentDirectory();
}
// Show the actual dialogue based on input path derived from stuff above
if (folderOpenDialogue.ShowDialog(this.Handle, throwOnError: false) == true)
{
// Store the selected folder path to use next time
lastSelectedFolderPath = folderOpenDialogue.ResultPath;
}
return folderOpenDialogue.ResultPath;
}
private void txtFramesFolderDetails_TextChanged(object sender, EventArgs e)
{
}
private void txtFramesFolderPath_TextChanged(object sender, EventArgs e)
{
// Hide the GIF creation status label if it was visible
labelGifCreateStatus.Visible = false;
// Check if the folder path is valid, if so get list of files
if (!Directory.Exists(txtFramesFolderPath.Text))
{
txtFramesFolderDetails.Text = "Invalid folder path";
btnViewOutputDirectory.Enabled = false;
return;
}
else
{
btnViewOutputDirectory.Enabled = true;
}
UpdateFolderDetails();
}
// Get folder details and optionally update the text box
private void UpdateFolderDetails()
{
string folderPath = txtFramesFolderPath.Text;
string[] allFiles = Directory.GetFiles(folderPath);
int totalFilesCount = allFiles.Length;
string folderBaseName = Path.GetFileName(folderPath);
// Get list of all the png files in the folder
string[] pngFiles = Directory.GetFiles(folderPath, "*.png");
string[] gifFiles = Directory.GetFiles(folderPath, "*.gif");
int pngFilesCount = pngFiles.Length;
int gifFilesCount = gifFiles.Length;
txtFramesFolderDetails.Text = $"--- Files Found in \"{folderBaseName}\": ---\r\n PNG Frames: {pngFilesCount}\r\n GIFs: {gifFilesCount}";
currentFramesInFolder = pngFilesCount;
UpdateTotalDurationLabel();
}
private void buttonImportAnotherFolder_Click(object sender, EventArgs e)
{
string outputDirToMergeInto = txtFramesFolderPath.Text;
if (string.IsNullOrEmpty(outputDirToMergeInto))
{
// Show message box if no output directory is selected
MessageBox.Show("Please select a folder above first. That is where any imported frames will be added when you use this button.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
string folderToImportPath = FolderSelector(tryLastSelection: true);
if (string.IsNullOrEmpty(folderToImportPath))
{
return;
}
FileManager fileManager = new FileManager();
fileManager.ImportAndMergeFolders(existingFolderPath: outputDirToMergeInto, importFolderPath: folderToImportPath);
UpdateFolderDetails();
}
private void buttonFixFileSequence_Click(object sender, EventArgs e)
{
// Use FileManager's Update Zero Padding method to fix the file sequence if necessary in current folder
string folderPath = txtFramesFolderPath.Text;
if (string.IsNullOrEmpty(folderPath))
{
// Show message box if no output directory is selected
MessageBox.Show("First you must select a folder above that contains the image frame files to process.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
FileManager fileManager = new FileManager();
string baseFileName = fileManager.GetBaseFileNameWithinFolder(folderPath);
SequenceFixResult sequenceFixResult = fileManager.FixDiscontinuousSequence(folderPath, baseFileName);
PaddingUpdateResult paddingUpdateResult = fileManager.UpdateZeroPadding(folderPath, baseFileName);
// Prepare message content based on the results
string message = "Operation Summary:\n";
// Append results from sequence fixing
if (sequenceFixResult.ChangesMade)
{
message += $"Files resequenced: {sequenceFixResult.FilesRenamed}.\n";
}
else
{
message += "No resequencing needed.\n";
}
// Append results from padding update
if (paddingUpdateResult.ChangesMade)
{
message += $"Files re-padded: {paddingUpdateResult.FilesRenamed}.\n";
message += $"New format used: {paddingUpdateResult.NewFormat}.\n";
}
else
{
message += "No re-padding needed.\n";
}
// Append errors if any
if (sequenceFixResult.Errors.Any() || paddingUpdateResult.Errors.Any())
{
message += "Errors encountered:\n";
foreach (var error in sequenceFixResult.Errors)
{
message += $"{error}\n";
}
foreach (var error in paddingUpdateResult.Errors)
{
message += $"{error}\n";
}
}
// Display the results in a single message box
MessageBox.Show(message, "Operation Results", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private string CreateGif(string outputDir, int frameRate = 25)
{
// Check if ffmpeg.exe exists, will display message if not
CheckIfFileInSystemPathOrDirectory(fileNameToCheck: "ffmpeg.exe", silent: false);
FileManager fileManager = new FileManager();
string baseFileName = fileManager.GetBaseFileNameWithinFolder(outputDir, "*.png");
// Execute ffmpeg.exe to create GIF
//string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(inputFilePath);
int totalFrames = Directory.GetFiles(outputDir, "*.png").Length;
int digitCount = (int)Math.Floor(Math.Log10(totalFrames)) + 1;
// Decide on name for file to not overwrite gif file
int i = 2;
string gifFileName = $"animated_{baseFileName}.gif";
while (File.Exists(Path.Combine(outputDir, gifFileName)))
{
gifFileName = $"animated_{baseFileName}_{i}.gif";
i++;
}
// Determine which command to run based on dropdown selection
string ffmpegCommand = "";
int alphaThreshold = (int)nudAlphaThreshold.Value;
if (dropdownFFmpegMode.SelectedIndex == 0)
{
ffmpegCommand = $"ffmpeg -framerate {frameRate} -reinit_filter 0 -i \"{outputDir}\\{baseFileName}_%0{digitCount}d.png\" -gifflags -transdiff -gifflags +offsetting -filter_complex \"[0:v] split [a][b];[a] palettegen=reserve_transparent=on:transparency_color=ffffff [p];[b][p] paletteuse=alpha_threshold={alphaThreshold}\" \"{outputDir}\\{gifFileName}\"";
}
else if (dropdownFFmpegMode.SelectedIndex == 1)
{
ffmpegCommand = $"ffmpeg -framerate {frameRate} -i \"{outputDir}\\{baseFileName}_%0{digitCount}d.png\" \"{outputDir}\\{gifFileName}\"";
}
bool logffmpeg = false;
string logFilePath = "ffmpeg_log.txt";
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "cmd.exe";
if (logffmpeg)
{
startInfo.Arguments = $"/c {ffmpegCommand} > {logFilePath} 2>&1";
}
else
{
startInfo.Arguments = $"/c {ffmpegCommand}";
}
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
using (Process process = new Process())
{
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
}
bool gifCreated = File.Exists(Path.Combine(outputDir, gifFileName));
if (gifCreated)
{
return gifFileName;
}
else
{
return null;
}
}
private void buttonCreateGifFromFolder_Click(object sender, EventArgs e)
{
// Check if valid folder
if (!Directory.Exists(txtFramesFolderPath.Text))
{
MessageBox.Show("You must select a folder with the frames to combine above first.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
string createdFile = CreateGif(txtFramesFolderPath.Text, (int)nudFrameRateSelect.Value);
if (createdFile != null)
{
// Display green message if GIF created
labelGifCreateStatus.Visible = true;
labelGifCreateStatus.ForeColor = Color.Green;
labelGifCreateStatus.Text = $"GIF Created: {createdFile}";
}
else
{
labelGifCreateStatus.Visible = true;
labelGifCreateStatus.ForeColor = Color.Red;
labelGifCreateStatus.Text = $"Error Occurred Trying to Create: {createdFile}";
}
}
private void UpdateTotalDurationLabel()
{
if (currentFramesInFolder > 0)
{
double totalDuration = (double)(currentFramesInFolder / (double)nudFrameRateSelect.Value);
labelCalcGifDuration.Text = $"Total Duration: {totalDuration:F2} s";
}
else
{
labelCalcGifDuration.Text = "Total Duration: N/A";
}
}
private void nudFrameRateSelect_ValueChanged(object sender, EventArgs e)
{
UpdateTotalDurationLabel();
}
private void buttonAddCrossfade_Click(object sender, EventArgs e)
{
// Check if ffmpeg .exe exists, will display message if not
bool ffmpegAvailable = CheckIfFileInSystemPathOrDirectory(fileNameToCheck: "ffmpeg.exe", silent: false);
if (!ffmpegAvailable)
{
return;
}
// Ensure the input file path is valid
if (!File.Exists(txtGifFilePath.Text))
{
MessageBox.Show("You must select a valid GIF file first.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
ApplyCrossfadeEffect(inputFilePath: txtGifFilePath.Text, fadeDurationSeconds: (double)nudFadeDurationSeconds.Value);
}
private void nudFadeDurationSeconds_ValueChanged(object sender, EventArgs e)
{
labelCrossfadeStatus.Visible = false;
}
private void buttonCreationHelp_Click(object sender, EventArgs e)
{
// Pop up a message box
MessageBox.Show("Requirements:\n\n" +
"• ffmpeg.exe is needed to combine the images into an animated gif.\n\n" +
"Instructions:\n\n" +
"1. Select a folder containing png frames outputted by the G'mic Animator app.\n" +
"2. Any optional steps (see below).\n" +
"3. To create an animated Gif using the files in the folder, choose a desired frame rate and click \"Create GIF From Folder\".\n\n" +
"Optional: If you want to add the frames from another animation folder onto those in the currently selected folder, click \"Import Folder\"" +
" and select the folder with the new frames to add. It will automatically rename the files as necessary and make the file names all one sequence.\n\n" +
"Optional: If you are having issues when generating a gif because you deleted some frames in the middle, or " +
"because the filename numbers have inconsistent sequence formats (01 vs 001 for example), then click \"Fix File Sequence\" to rename them in a continuous sequence.\n\n" +
"The GIF will be created in the same folder as the PNG frames - They will be automatically named to not overwrite each other.",
"GIF Creation Help",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
private void buttonEditHelp_Click(object sender, EventArgs e)
{
// Pop up a message box
MessageBox.Show("Requirements:\n\n" +
"• ffmpeg.exe is needed to apply the crossfade effect.\n" +
"• ffprobe.exe (which comes with ffmpeg) is needed to get the stats about the gif necessary for calcualting the crossfade.\n\n" +
"Crossfade Loop Effect Instructions:\n\n" +
"1. Select an animated Gif file - The box will display some information about it.\n" +
"2. Select the duration of the crossfade. You'll want to experiment with this to see what looks best for each animation.\n" +
"3. To apply a cross-fade effect at the loop point of the Gif, click \"Add Loop Crossfade\".\n\n" +
"The new gif will be created alongside the current one - They will be automatically named to not overwrite each other.",
"GIF Edit Help",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
private void btnViewOutputDirectory_Click(object sender, EventArgs e)
{
// Open the folder in Windows Explorer
string folderPath = txtFramesFolderPath.Text;
if (Directory.Exists(folderPath))
{
Process.Start("explorer.exe", folderPath);
}
else
{
MessageBox.Show("The folder path is invalid.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnCheckAlpha_Click(object sender, EventArgs e)
{
string gifFilePath = txtGifFilePath.Text;
List<Dictionary<string, object>> pixelData = FileManager.CheckAlphaChannel(gifFilePath, countAll: true);
if (pixelData.Count == 0)
{
MessageBox.Show("No visible pixels found.", "Alpha Channel Found", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
//MessageBox.Show($"Found {pixelData.Count} visible pixels.", "No Alpha Channel Found", MessageBoxButtons.OK, MessageBoxIcon.Information);
ShowCustomMessageBox(pixelData);
}
}
static void ShowCustomMessageBox(List<Dictionary<string, object>> pixelData)
{
Form messageBox = new Form();
messageBox.Text = "No Alpha Channel Found";
messageBox.StartPosition = FormStartPosition.CenterScreen;
messageBox.Width = 400;
messageBox.Height = 200;
Label messageLabel = new Label();
messageLabel.Text = $"Found {pixelData.Count} visible pixels.";
messageLabel.AutoSize = true;
messageLabel.Location = new Point(10, 20);
messageBox.Controls.Add(messageLabel);
Button okButton = new Button();
okButton.Text = "OK";
okButton.DialogResult = DialogResult.OK;
okButton.Location = new Point(50, 80);
messageBox.Controls.Add(okButton);
Button saveButton = new Button();
saveButton.Text = "Save to Log";
saveButton.Location = new Point(150, 80);
saveButton.Size = new Size(100, 30);
saveButton.Click += (sender, e) => SaveDataToLogFile(pixelData);
messageBox.Controls.Add(saveButton);
messageBox.AcceptButton = okButton;
messageBox.ShowDialog();
}
static void SaveDataToLogFile(List<Dictionary<string, object>> pixelData)
{
string logFilePath = "pixelDataLog.txt";
using (StreamWriter writer = new StreamWriter(logFilePath))
{
foreach (var pixel in pixelData)
{
writer.WriteLine($"X: {pixel["X"]}, Y: {pixel["Y"]}, A: {pixel["A"]}, R: {pixel["R"]}, G: {pixel["G"]}, B: {pixel["B"]}");
}
}
MessageBox.Show("Data saved to log file.", "Save Successful", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void labelFrameRateSelect_Click(object sender, EventArgs e)
{
}
}
}