Ejemplo n.º 1
0
/// <summary>
/// Get the new dimensions of a photo or video based on the options requested.
/// </summary>
/// <param name="resizeOption">How to interpret the parameter resizeValue.</param>
/// <param name="width">The width of the original media.</param>
/// <param name="height">The height of the original media.</param>
/// <param name="resizeValue">The value to resize to interpreted in the way specified by resizeOption</param>
/// <returns>A tuple containing the dimensions of the new image.</returns>
        private static Tuple <int, int> GetNewSize(comboOptions resizeOption, int width, int height, int resizeValue)
        {
            int newWidth  = 0;
            int newHeight = 0;

            switch (resizeOption)
            {
            case comboOptions.percent:
                newWidth  = width * resizeValue / 100;
                newHeight = height * resizeValue / 100;
                break;

            case comboOptions.height:
                newHeight = resizeValue;
                newWidth  = width * resizeValue / height;
                break;

            case comboOptions.width:
                newHeight = height * resizeValue / width;
                newWidth  = resizeValue;
                break;
            }
            if (newWidth == 0 || newHeight == 0)
            {
                throw new Exception("New image is too small.");
            }
            return(new Tuple <int, int>(newWidth, newHeight));
        }
Ejemplo n.º 2
0
 public MediaProcessorOptions(comboOptions imageResizeType,
                              comboOptions videoResizeType,
                              outTypeOptions imageOutType,
                              videoOutTypeOptions videoOutType,
                              int imageResizeValue,
                              int videoResizeValue,
                              int jpegQuality,
                              int videoQuality,
                              float?defaultDropRatio)
 {
     this.imageResizeType  = imageResizeType;
     this.videoResizeType  = videoResizeType;
     this.imageOutType     = imageOutType;
     this.videoOutType     = videoOutType;
     this.imageResizeValue = imageResizeValue;
     this.videoResizeValue = videoResizeValue;
     this.jpegQuality      = jpegQuality;
     this.videoQuality     = videoQuality;
     this.defaultCropRatio = defaultDropRatio;
 }
Ejemplo n.º 3
0
        private int TryReadResizeText(TextBox txtBox, comboOptions comboIdx)
        {
            int  x;
            bool success = int.TryParse(txtBox.Text, out x);

            if (success)
            {
                switch (comboIdx)
                {
                case comboOptions.percent:
                    if (x < 1 || x > 1000)
                    {
                        x = -1;
                    }
                    break;

                case comboOptions.height:
                    if (x < 1 || x > 10000)
                    {
                        x = -1;
                    }
                    break;

                case comboOptions.width:
                    if (x < 1 || x > 10000)
                    {
                        x = -1;
                    }
                    break;
                }
                ;
            }
            else
            {
                x = -1;
            }
            return(x);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Parse a text value into a valid resize integer.
        /// </summary>
        /// <param name="resizeText">Text to parse</param>
        /// <param name="resizeType">How the text should be interpreted</param>
        /// <param name="result">Integer to parse the result into, if successful</param>
        /// <returns>Boolean indicating success.</returns>
        public static bool TryParseResizeValue(string resizeText, comboOptions resizeType, out int result)
        {
            int  x;
            bool success = int.TryParse(resizeText, out x);

            if (success)
            {
                switch (resizeType)
                {
                case comboOptions.percent:
                    if (x < 1 || x > 1000)
                    {
                        success = false; x = 0;
                    }
                    break;

                case comboOptions.height:
                    if (x < 1 || x > 10000)
                    {
                        success = false; x = 0;
                    }
                    break;

                case comboOptions.width:
                    if (x < 1 || x > 10000)
                    {
                        success = false; x = 0;
                    }
                    break;
                }
                ;
            }

            result = x;
            return(success);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Resize, trim, and save a video file.
        /// </summary>
        /// <param name="filename">Full path to the video to resize.</param>
        /// <param name="outFile">Full path to where the output file should be saved.</param>
        /// <param name="resizeValue">The height, width, or precentage to resize to, as specified by the resizeOption parameter.</param>
        /// <param name="resizeOption">The type of resize which resizeValue is referring to.</param>
        /// <param name="outTypeOption">The output video file type.</param>
        /// <param name="videoQuality">The quality of the output video. A value of 100 means 8kbps for full HD (1980x1080)</param>
        /// <param name="trimRange">The range, in seconds, to trim the video clip to. Set to null to not trim the clip.</param>
        /// <param name="jobProgressCallback">Delegate function which is called at regular intervals for progress updates during the job.</param>
        /// <returns>Void.</returns>
        private static void ProcessVideoFile(string filename, string outFile, int resizeValue, comboOptions resizeOption,
                                             videoOutTypeOptions outTypeOption = videoOutTypeOptions.WMV,
                                             int videoQuality = 100,
                                             Tuple <double, double> trimRange = null,
                                             VideoProgressDelegateCallback jobProgressCallback = null)
        {
            Job       j            = new Job();
            MediaItem mediaItem    = new MediaItem(filename);
            var       originalSize = mediaItem.OriginalVideoSize;
            // Get new dimensions
            Tuple <int, int> newSize = GetNewSize(resizeOption, originalSize.Width, originalSize.Height, resizeValue);
            // Round to the nearest 4 pixels - this is required by encoder
            // Encoder says the value must be an even integer between 64 and 4096 and a multiple of 4
            int newWidth  = Convert.ToInt32(Math.Round(newSize.Item1 / 4.0) * 4);
            int newHeight = Convert.ToInt32(Math.Round(newSize.Item2 / 4.0) * 4);

            if (newWidth < 64 || newHeight < 64 || newWidth > 4096 || newHeight > 4096)
            {
                throw new Exception("New height and width must be between 64 and 4096 pixels");
            }

            double bitsPerSecondPerPixel = 8000.0 / 2000000.0;  // Assume 8kbps for full HD
            int    bitRate = Convert.ToInt32(bitsPerSecondPerPixel * videoQuality * newWidth * newHeight / 100);

            WindowsMediaOutputFormat outFormat = new WindowsMediaOutputFormat();

            outFormat.AudioProfile             = new Microsoft.Expression.Encoder.Profiles.WmaAudioProfile();
            outFormat.VideoProfile             = new Microsoft.Expression.Encoder.Profiles.AdvancedVC1VideoProfile();
            outFormat.VideoProfile.AspectRatio = mediaItem.OriginalAspectRatio;
            outFormat.VideoProfile.AutoFit     = true;
            outFormat.VideoProfile.Bitrate     = new Microsoft.Expression.Encoder.Profiles.VariableUnconstrainedBitrate(bitRate);
            outFormat.VideoProfile.Size        = new Size(newWidth, newHeight);

            mediaItem.VideoResizeMode = VideoResizeMode.Letterbox;
            mediaItem.OutputFormat    = outFormat;

            if (!(trimRange == null))
            {
                Source source = mediaItem.Sources[0];
                source.Clips[0].StartTime = TimeSpan.FromSeconds(trimRange.Item1);
                source.Clips[0].EndTime   = TimeSpan.FromSeconds(trimRange.Item2);
            }

            mediaItem.OutputFileName = Path.GetFileName(outFile);

            j.MediaItems.Add(mediaItem);
            j.CreateSubfolder = false;
            j.OutputDirectory = Path.GetDirectoryName(outFile);

            if (jobProgressCallback != null)
            {
                j.EncodeProgress += new EventHandler <EncodeProgressEventArgs>(jobProgressCallback);
            }
            j.Encode();
            j.Dispose();
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Resize and save an image file.
        /// </summary>
        /// <param name="filename">Full path to the image to resize.</param>
        /// <param name="outFile">Full path to where the output file should be saved.</param>
        /// <param name="resizeValue">The height, width, or precentage to resize to, as specified by the resizeOption parameter.</param>
        /// <param name="resizeOption">The type of resize which resizeValue is referring to.</param>
        /// <param name="outTypeOption">The output image file type.</param>
        /// <param name="jpegQuality">Only used if outTypeOption is JPEG, the quality parameter of the output JPEG image</param>
        /// <returns>Void.</returns>
        public static void ProcessImageFile(string filename, string outFile, int resizeValue, comboOptions resizeOption,
                                            outTypeOptions outTypeOption,
                                            Dictionary <string, Rectangle> definedCropBoundaries,
                                            float?defaultCropRatio, int jpegQuality = 98)
        {
            // Read file - will throw exception if file doesn't exist
            using (Image img = Image.FromFile(filename))
            {
                Rectangle cropBoundary = GetCropBoundaryForImage(filename, img, definedCropBoundaries, defaultCropRatio);

                // Get new dimensions
                Tuple <int, int> newSize = GetNewSize(resizeOption, cropBoundary.Width, cropBoundary.Height, resizeValue);
                int newWidth             = newSize.Item1;
                int newHeight            = newSize.Item2;

                // Do actual resize
                using (Bitmap resizedBmp = ResizeImage(img, newWidth, newHeight, cropBoundary))
                {
                    // Save result
                    if (outTypeOption == outTypeOptions.match)
                    {
                        switch (Path.GetExtension(filename).ToLower())
                        {
                        case ".jpg":
                        case ".jpeg":
                            outTypeOption = outTypeOptions.JPG;
                            break;

                        case ".bmp":
                            outTypeOption = outTypeOptions.BMP;
                            break;

                        case ".gif":
                            outTypeOption = outTypeOptions.GIF;
                            break;

                        case ".png":
                            outTypeOption = outTypeOptions.PNG;
                            break;

                        case ".tif":
                        case ".tiff":
                            outTypeOption = outTypeOptions.TIF;
                            break;
                        }
                    }
                    EncoderParameters eps = null;
                    ImageCodecInfo    ici = GetEncoderInfo("image/bmp");
                    switch (outTypeOption)
                    {
                    case outTypeOptions.JPG:
                        eps          = new EncoderParameters(1);
                        eps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)jpegQuality);
                        ici          = GetEncoderInfo("image/jpeg");
                        break;

                    case outTypeOptions.BMP:
                        // Nothing to do - defaults are fine
                        break;

                    case outTypeOptions.GIF:
                        ici = GetEncoderInfo("image/gif");
                        break;

                    case outTypeOptions.PNG:
                        ici = GetEncoderInfo("image/png");
                        break;

                    case outTypeOptions.TIF:
                        ici = GetEncoderInfo("image/tiff");
                        break;
                    }

                    foreach (PropertyItem propItem in img.PropertyItems)
                    {
                        resizedBmp.SetPropertyItem(propItem);
                    }

                    resizedBmp.Save(outFile, ici, eps);
                }
            }
        }
Ejemplo n.º 7
0
        private void btnProcess_Click(object sender, EventArgs e)
        {
            if (this.isProcessing)
            {
                this.cancelSource.Cancel();
                return;
            }
            if (this.fileList.Count == 0)
            {
                MessageBox.Show("No files selected.", "No files selected", MessageBoxButtons.OK);
                return;
            }
            int resizeValue = TryReadResizeText(this.txtResize, (comboOptions)this.cbxResizeType.SelectedIndex);

            if (resizeValue < 0)
            {
                MessageBox.Show("Invalid value entered for resizing images to.", "Invalid entry", MessageBoxButtons.OK);
                return;
            }
            int videoResizeValue = TryReadResizeText(this.txtVideoResize, (comboOptions)this.cbxVideoResizeType.SelectedIndex);

            if (videoResizeValue < 0)
            {
                MessageBox.Show("Invalid value entered for resizing videos to.", "Invalid entry", MessageBoxButtons.OK);
                return;
            }

            this.OnProcessingStart();



            comboOptions        comboOption        = (comboOptions)this.cbxResizeType.SelectedIndex;
            comboOptions        videoComboOption   = (comboOptions)this.cbxVideoResizeType.SelectedIndex;
            outTypeOptions      outTypeOption      = (outTypeOptions)this.cbxOutputType.SelectedIndex;
            videoOutTypeOptions videoOutTypeOption = (videoOutTypeOptions)this.cbxVideoOutputType.SelectedIndex;
            int jpegQuality         = (int)nudQuality.Value;
            int mpegQuality         = (int)nudVideoQuality.Value;
            CancellationToken token = this.cancelSource.Token;

            Task processingTask = Task.Factory.StartNew(() =>
            {
                List <string> failedList = new List <string>();
                for (int ii = 0; ii < this.fileList.Count; ii++)
                {
                    if (token.IsCancellationRequested)
                    {
                        break;
                    }
                    try
                    {
                        if (!IsVideoFile(this.fileList[ii]))
                        {
                            ProcessImageFile(this.fileList[ii], resizeValue, comboOption, outTypeOption, jpegQuality);
                        }
                        else
                        {
                            Tuple <double, double> trimRange = null;
                            int idx = this.trimFiles.FindIndex(a => a == this.fileList[ii]);
                            if (idx >= 0)
                            {
                                trimRange = this.trimRanges[idx];
                            }
                            ProcessVideoFile(this.fileList[ii], videoResizeValue, videoComboOption, videoOutTypeOption, mpegQuality, trimRange);
                        }
                        if (token.IsCancellationRequested)
                        {
                            break;
                        }
                        SetProgress(ii + 1);
                    }
                    catch (Exception exp)
                    {
                        Console.WriteLine(String.Format("{0} - {1}", exp.Message, exp.StackTrace));
                        failedList.Add(this.fileList[ii]);
                    }
                }
                if (token.IsCancellationRequested)
                {
                    this.OnProcessingCancelled();
                }
                else
                {
                    this.OnProcessingComplete(failedList.Count);
                }
            }, token);
        }
Ejemplo n.º 8
0
        private void ProcessImageFile(string filename, int resizeValue, comboOptions resizeOption,
                                      outTypeOptions outTypeOption, int jpegQuality)
        {
            SetCurrentProgress(0, filename);

            // Read file - will throw exception if file doesn't exist
            Image img = Image.FromFile(filename);

            string outFile = GetOutputFilename(filename, outTypeOption);

            EnsureDir(outFile); // Will throw exception if can't create folder
            DialogResult result = WarnIfExists(outFile);

            switch (result)
            {
            case DialogResult.Yes:
                break;

            case DialogResult.No:
                return;

            case DialogResult.Cancel:
                this.cancelSource.Cancel();
                return;
            }

            // Get new dimensions
            Tuple <int, int> newSize = GetNewSize(resizeOption, img.Width, img.Height, resizeValue);
            int newWidth             = newSize.Item1;
            int newHeight            = newSize.Item2;

            // Do actual resize
            Bitmap resizedBmp = ResizeImage(img, newWidth, newHeight);

            // Save result
            if (outTypeOption == outTypeOptions.match)
            {
                switch (Path.GetExtension(filename).ToLower())
                {
                case ".jpg":
                case ".jpeg":
                    outTypeOption = outTypeOptions.JPG;
                    break;

                case ".bmp":
                    outTypeOption = outTypeOptions.BMP;
                    break;

                case ".gif":
                    outTypeOption = outTypeOptions.GIF;
                    break;

                case ".png":
                    outTypeOption = outTypeOptions.PNG;
                    break;

                case ".tif":
                case ".tiff":
                    outTypeOption = outTypeOptions.TIF;
                    break;
                }
            }
            EncoderParameters eps = null;
            ImageCodecInfo    ici = GetEncoderInfo("image/bmp");

            switch (outTypeOption)
            {
            case outTypeOptions.JPG:
                eps          = new EncoderParameters(1);
                eps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)jpegQuality);
                ici          = GetEncoderInfo("image/jpeg");
                break;

            case outTypeOptions.BMP:
                // Nothing to do - defaults are fine
                break;

            case outTypeOptions.GIF:
                ici = GetEncoderInfo("image/gif");
                break;

            case outTypeOptions.PNG:
                ici = GetEncoderInfo("image/png");
                break;

            case outTypeOptions.TIF:
                ici = GetEncoderInfo("image/tiff");
                break;
            }

            foreach (PropertyItem propItem in img.PropertyItems)
            {
                resizedBmp.SetPropertyItem(propItem);
            }

            resizedBmp.Save(outFile, ici, eps);
        }
Ejemplo n.º 9
0
        private void ProcessVideoFile(string filename, int resizeValue, comboOptions resizeOption,
                                      videoOutTypeOptions outTypeOption, int mpegQuality, Tuple <double, double> trimRange)
        {
            SetCurrentProgress(0, filename);

            // TODO - check if input file exists

            string outFile = GetOutputFilename(filename, outTypeOption);

            EnsureDir(outFile); // Will throw exception if can't create folder
            DialogResult result = WarnIfExists(outFile);

            switch (result)
            {
            case DialogResult.Yes:
                break;

            case DialogResult.No:
                return;

            case DialogResult.Cancel:
                this.cancelSource.Cancel();
                return;
            }

            Job       j            = new Job();
            MediaItem mediaItem    = new MediaItem(filename);
            var       originalSize = mediaItem.OriginalVideoSize;
            // Get new dimensions
            Tuple <int, int> newSize = GetNewSize(resizeOption, originalSize.Width, originalSize.Height, resizeValue);
            // Round to the nearest 4 pixels - this is required by encoder
            // Encoder says the value must be an even integer between 64 and 4096 and a multiple of 4
            int newWidth  = Convert.ToInt32(Math.Round(newSize.Item1 / 4.0) * 4);
            int newHeight = Convert.ToInt32(Math.Round(newSize.Item2 / 4.0) * 4);

            if (newWidth < 64 || newHeight < 64 || newWidth > 4096 || newHeight > 4096)
            {
                throw new Exception("New height and width must be between 64 and 4096 pixels");
                // TODO - display this in the status bar
            }

            double bitsPerSecondPerPixel = 8000.0 / 2000000.0;  // Assume 8kbps for full HD
            int    bitRate = Convert.ToInt32(bitsPerSecondPerPixel * mpegQuality * newWidth * newHeight / 100);

            WindowsMediaOutputFormat outFormat = new WindowsMediaOutputFormat();

            outFormat.AudioProfile = new Microsoft.Expression.Encoder.Profiles.WmaAudioProfile();
            // outFormat.VideoProfile = new Microsoft.Expression.Encoder.Profiles.MainVC1VideoProfile();
            outFormat.VideoProfile             = new Microsoft.Expression.Encoder.Profiles.AdvancedVC1VideoProfile();
            outFormat.VideoProfile.AspectRatio = mediaItem.OriginalAspectRatio;
            outFormat.VideoProfile.AutoFit     = true;
            outFormat.VideoProfile.Bitrate     = new Microsoft.Expression.Encoder.Profiles.VariableUnconstrainedBitrate(bitRate);
            outFormat.VideoProfile.Size        = new Size(newWidth, newHeight);

            //mediaItem.VideoResizeMode = VideoResizeMode.Letterbox;

            mediaItem.OutputFormat = outFormat;

            if (!(trimRange == null))
            {
                Source source = mediaItem.Sources[0];
                source.Clips[0].StartTime = TimeSpan.FromSeconds(trimRange.Item1);
                source.Clips[0].EndTime   = TimeSpan.FromSeconds(trimRange.Item2);
            }

            mediaItem.OutputFileName = Path.GetFileName(outFile);

            j.MediaItems.Add(mediaItem);
            j.CreateSubfolder = false;
            j.OutputDirectory = Path.GetDirectoryName(outFile);

            j.EncodeProgress += new EventHandler <EncodeProgressEventArgs>(OnJobEncodeProgress);
            j.Encode();
            j.Dispose();
        }