BarcodeGenerator.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using ImageMagick;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace MovieBarcodeGenerator {
  10. public class BarcodeGenerator {
  11. public static string imagickPath;
  12. private static log4net.ILog log = log4net.LogManager.GetLogger("Generator");
  13. public static string ffmpegPath {
  14. get {
  15. return SharpFF.ffmpegPath;
  16. }
  17. set {
  18. SharpFF.ffmpegPath = value;
  19. }
  20. }
  21. public static void Generate(string inputFile, string outputFile, int height, int width) {
  22. Generate(inputFile, outputFile, height, 1, width);
  23. }
  24. public static void Generate(string inputFile, string outputFile, int height, int barWidth, int iterations) {
  25. log.Debug("Generate()");
  26. if (File.Exists(outputFile)) {
  27. log.InfoFormat("Output file '{0}' exists. Deleting file.", outputFile);
  28. File.Delete(outputFile);
  29. }
  30. // set the path because .Net uses the "convert" utility on Windows by default
  31. System.Environment.SetEnvironmentVariable("Path", imagickPath);
  32. decimal videoLength = SharpFF.GetDuration(inputFile);
  33. // run these in parallel to save time
  34. // TODO: do all this work in a temp folder, then move the finished file to the destination
  35. Parallel.For(0, iterations, i => {
  36. string timecodeAt = SharpFF.SecondsToTimecode(i * (videoLength / iterations));
  37. SharpFF.ExecuteCommand(string.Format("-hide_banner -loglevel panic -nostats -y -ss {1} -i \"{0}\" -vframes 1 -an -f rawvideo -vcodec png -vf scale={4}:{5} \"{2}\\out_{3:000}.png\"", inputFile, timecodeAt, Path.GetDirectoryName(outputFile), i, barWidth, height));
  38. });
  39. log.Debug("Scrunching PNGs together.");
  40. // use ImageMagick to crush the generated PNGs together
  41. using (MagickImageCollection images = new MagickImageCollection()) {
  42. foreach (var file in Directory.GetFiles(Path.GetDirectoryName(outputFile), "out_???.png")) {
  43. images.Add(new MagickImage(file));
  44. }
  45. // create a strip from all those images
  46. using (IMagickImage result = images.AppendHorizontally()) {
  47. // Save the result
  48. result.Write(outputFile);
  49. }
  50. }
  51. log.Debug("Deleting temporary work files.");
  52. // clean up the work files
  53. string[] files = Directory.GetFiles(Path.GetDirectoryName(outputFile), "out_???.png");
  54. foreach (string file in files) {
  55. File.Delete(file);
  56. }
  57. }
  58. }
  59. }