BarcodeGenerator.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. public static string imagickPath;
  13. private static log4net.ILog log = log4net.LogManager.GetLogger("Generator");
  14. public static string ffmpegPath {
  15. get {
  16. return SharpFF.ffmpegPath;
  17. }
  18. set {
  19. SharpFF.ffmpegPath = value;
  20. }
  21. }
  22. public static void Generate(string inputFile, string outputFile, int height, int width) {
  23. Generate(inputFile, outputFile, height, 1, width);
  24. }
  25. public static void Generate(string inputFile, string outputFile, int height, int barWidth, int iterations) {
  26. log.InfoFormat("Beginning barcode generation for {0} slices.", iterations);
  27. if (File.Exists(outputFile)) {
  28. log.InfoFormat("Output file '{0}' exists. Deleting file.", outputFile);
  29. File.Delete(outputFile);
  30. }
  31. // set the path because .Net uses the "convert" utility on Windows by default
  32. System.Environment.SetEnvironmentVariable("Path", imagickPath);
  33. decimal videoLength = SharpFF.GetDuration(inputFile);
  34. // run these in parallel to save time
  35. // TODO: do all this work in a temp folder, then move the finished file to the destination
  36. log.Debug("Generating image slices.");
  37. Parallel.For(0, iterations, i => {
  38. string timecodeAt = SharpFF.SecondsToTimecode(i * (videoLength / iterations));
  39. 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));
  40. });
  41. log.Debug("Appending image files.");
  42. // use ImageMagick to crush the generated PNGs together
  43. using (MagickImageCollection images = new MagickImageCollection()) {
  44. foreach (var file in Directory.GetFiles(Path.GetDirectoryName(outputFile), "out_???.png")) {
  45. images.Add(new MagickImage(file));
  46. }
  47. // create a strip from all those images
  48. using (IMagickImage result = images.AppendHorizontally()) {
  49. // Save the result
  50. result.Write(outputFile);
  51. }
  52. }
  53. log.Info("Cleaning up temporary files.");
  54. // clean up the work files
  55. string[] files = Directory.GetFiles(Path.GetDirectoryName(outputFile), "out_???.png");
  56. foreach (string file in files) {
  57. File.Delete(file);
  58. }
  59. }
  60. }
  61. }