public Bitmap CreateBarCode( string inputPath, BarCodeParameters parameters, FfmpegWrapper ffmpeg, CancellationToken cancellationToken, IProgress <double> progress = null) { Bitmap finalBitmap = null; Graphics finalBitmapGraphics = null; Graphics GetDrawingSurface(int width, int height) { if (finalBitmap == null) { finalBitmap = new Bitmap(width, height); finalBitmapGraphics = Graphics.FromImage(finalBitmap); } return(finalBitmapGraphics); } var barCount = (int)Math.Round((double)parameters.Width / parameters.BarWidth); var source = ffmpeg.GetImagesFromMedia(inputPath, barCount, cancellationToken); int?finalBitmapHeight = null; int x = 0; foreach (var image in source) { if (finalBitmapHeight == null) { finalBitmapHeight = parameters.Height ?? image.Height; } var surface = GetDrawingSurface(parameters.Width, finalBitmapHeight.Value); surface.DrawImage(image, x, 0, parameters.BarWidth, finalBitmapHeight.Value); x += parameters.BarWidth; progress?.Report((double)x / parameters.Width); image.Dispose(); } finalBitmapGraphics?.Dispose(); return(finalBitmap); }
GetValidatedParameters() { var inputPath = inputPathTextBox.Text.Trim(new[] { '"' }); if (!File.Exists(inputPath)) { throw new Exception("The input file does not exist."); } var outputPath = outputPathTextBox.Text.Trim(new[] { '"' }); void ValidateOutputPath(ref string path) { if (string.IsNullOrWhiteSpace(path)) { path = "output.png"; } if (!Path.HasExtension(path)) { path += ".png"; } if (path.Any(x => Path.GetInvalidPathChars().Contains(x))) { throw new Exception("The output path is invalid."); } if (File.Exists(path)) { var promptResult = MessageBox.Show(this, $"The file '{path}' already exists. Do you want to overwrite it?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (promptResult != DialogResult.Yes) { throw new OperationCanceledException(); } } } ValidateOutputPath(ref outputPath); string smoothedOutputPath = null; if (smoothCheckBox.Checked) { var name = $"{Path.GetFileNameWithoutExtension(outputPath)}_smoothed{Path.GetExtension(outputPath)}"; smoothedOutputPath = Path.Combine(Path.GetDirectoryName(outputPath), name); ValidateOutputPath(ref smoothedOutputPath); } if (!int.TryParse(barWidthTextBox.Text, out var barWidth) || barWidth <= 0) { throw new Exception("Invalid bar width."); } if (!int.TryParse(imageWidthTextBox.Text, out var imageWidth) || imageWidth <= 0) { throw new Exception("Invalid output width."); } int?imageHeight = null; if (!useInputHeightForOutputCheckBox.Checked) { if (int.TryParse(imageHeightTextBox.Text, out var nonNullableImageHeight) && nonNullableImageHeight > 0) { imageHeight = nonNullableImageHeight; } else { throw new Exception("Invalid output height."); } } var parameters = new BarCodeParameters() { BarWidth = barWidth, Width = imageWidth, Height = imageHeight }; return(inputPath, outputPath, smoothedOutputPath, parameters); }