BarcodeGenerator.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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;
  9. using System.Threading.Tasks;
  10. namespace MovieBarcodeGenerator {
  11. public class BarcodeGenerator {
  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.InfoFormat("Beginning barcode generation for {0} slices.", iterations);
  26. if (File.Exists(outputFile)) {
  27. log.InfoFormat("Output file '{0}' exists. Deleting file.", outputFile);
  28. File.Delete(outputFile);
  29. }
  30. decimal videoLength = SharpFF.GetDuration(inputFile);
  31. // run these in parallel to save time
  32. // TODO: do all this work in a temp folder, then move the finished file to the destination
  33. log.Debug("Generating image slices.");
  34. Parallel.For(0, iterations, i => {
  35. string timecodeAt = SharpFF.SecondsToTimecode(i * (videoLength / iterations));
  36. 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));
  37. });
  38. log.Debug("Appending image files.");
  39. // use ImageMagick to crush the generated PNGs together
  40. using (MagickImageCollection images = new MagickImageCollection()) {
  41. foreach (var file in Directory.GetFiles(Path.GetDirectoryName(outputFile), "out_???.png")) {
  42. images.Add(new MagickImage(file));
  43. }
  44. // create a strip from all those images
  45. using (IMagickImage result = images.AppendHorizontally()) {
  46. // Save the result
  47. result.Write(outputFile);
  48. }
  49. }
  50. log.Info("Cleaning up temporary files.");
  51. // clean up the work files
  52. string[] files = Directory.GetFiles(Path.GetDirectoryName(outputFile), "out_???.png");
  53. foreach (string file in files) {
  54. File.Delete(file);
  55. }
  56. }
  57. }
  58. }