Archive for the ‘Asset Management’ Category

Image Resizing and Cropping in C#

So the other day I put up a c# wrapper for ffmpeg. The wrapper I built is a part of my own asset storage system which I guess I will probably be putting up in chunks over the next few weeks. Today I have decided to put up my image resizing tools for your use.

Resize Now or Resize Later?

There are a couple theories to image resizing, should the image be resized at the point it gets uploaded, or at the point it gets sent out to the client?

Each method has advantages and disadvantages. Resizing at upload is good because it speeds up time to delivery as the processor has already done the resizing, additionally, the image is only resized once, vs. if the image is resized every time it is downloaded, it could be resized countless times. The problem with resizing at upload, however, is that it is now resized — you can’t un-resize it. Resizing at download then, is more processor intensive as it is resized every time someone requests a different size (one could probably get around some of this with caching, but the no matter how you slice it, it is still more processor intensive). The nice thing is that based on querystring or, however you pass the resizer data, you get a customized image size.

I have my own theory on this. If one has a ton of storage space (which most of us do have available to us now adays) it makes sense to resize in some basic sizes at upload while keeping the original as well for future resizing, if needed. Most good graphic designers break all their pages up into grids of magic 3rds anyways and would, generally, have ideas about their perfect image sizes for thumbnails, swatches, large previews, etc..

In another post I will detail how I get all of these different sizes and what not stored for use, but — for now — I will just give you the tools with which to do resizing and cropping in one spot.


//Overload for crop that default starts top left of the image.
public static System.Drawing.Image CropImage(System.Drawing.Image Image, int Height, int Width)
{
	return CropImage(Image, Height, Width, 0,0);
}

//The crop image sub
public static System.Drawing.Image CropImage(System.Drawing.Image Image, int Height, int Width, int StartAtX, int StartAtY)
{
	Image outimage;
	MemoryStream mm = null;
	try
	{
		//check the image height against our desired image height
		if (Image.Height < Height) {
			Height = Image.Height;
		}
		
		if (Image.Width < Width) {
			Width = Image.Width;
		}
		
		//create a bitmap window for cropping
		Bitmap bmPhoto = new Bitmap(Width, Height, PixelFormat.Format24bppRgb);
		bmPhoto.SetResolution(72, 72);
		
		//create a new graphics object from our image and set properties
		Graphics grPhoto = Graphics.FromImage(bmPhoto);
		grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
		grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
		grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality;
		
		//now do the crop
		grPhoto.DrawImage(Image, new Rectangle(0, 0, Width, Height), StartAtX, StartAtY, Width, Height, GraphicsUnit.Pixel);
		
		// Save out to memory and get an image from it to send back out the method.
		mm = new MemoryStream();
		bmPhoto.Save(mm, System.Drawing.Imaging.ImageFormat.Jpeg);
		Image.Dispose();
		bmPhoto.Dispose();
		grPhoto.Dispose();
		outimage = Image.FromStream(mm);

		return outimage;
	}
	catch (Exception ex)
	{
		throw new Exception("Error cropping image, the error was: " + ex.Message);
	}
}

//Hard resize attempts to resize as close as it can to the desired size and then crops the excess
public static System.Drawing.Image HardResizeImage(int Width, int Height, System.Drawing.Image Image)
{
	int width = Image.Width;
	int height = Image.Height;
	Image resized = null;
	if (Width > Height)
	{
		resized = ResizeImage(Width, Width, Image);
	}
	else
	{
		resized = ResizeImage(Height, Height, Image);
	}
	Image output = CropImage(resized, Height, Width);
	//return the original resized image
	return output;
}

//Image resizing
public static System.Drawing.Image ResizeImage(int maxWidth, int maxHeight, System.Drawing.Image Image)
{
	int width = Image.Width;
	int height = Image.Height;
	if (width > maxWidth || height > maxHeight)
	{
		//The flips are in here to prevent any embedded image thumbnails -- usually from cameras
		//from displaying as the thumbnail image later, in other words, we want a clean
		//resize, not a grainy one.
		Image.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipX);
		Image.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipX);

		float ratio = 0;
		if (width > height)
		{
			ratio = (float)width / (float)height;
			width = maxWidth;
			height = Convert.ToInt32(Math.Round((float)width / ratio));
		}
		else
		{
			ratio = (float)height / (float)width;
			height = maxHeight;
			width = Convert.ToInt32(Math.Round((float)height / ratio));
		}

		//return the resized image
		return Image.GetThumbnailImage(width, height, null, IntPtr.Zero);
	}
	//return the original resized image
	return Image;
}

Extenders

Yesterday I posted on extenders after seeing this great post http://blog.wekeroad.com/2010/01/20/my-favorite-helpers-for-aspnet-mvc. It strikes me that so much of what we do can be thrown into extenders. The code above, for example could really simply be used as extenders for you existing System.Drawing.Imaging objects.

public static string Crop(this System.Drawing.Imaging ThisImage, int maxHeight, int maxWidth)
{
    return CropImage(ThisImage, maxHeight, maxWidth);
}

public static string Resize(this System.Drawing.Imaging ThisImage, int Height, int Width)
{
    return ResizeImage(Width, Height, ThisImage);
}

public static string HardResize(this System.Drawing.Imaging ThisImage, int Height, int Width)
{
    return HardResizeImage(Width, Height, ThisImage);
}
Advertisements

A Simple c# Wrapper for ffMpeg

Converting video in .Net is a pain in the butt. The .Net framework, as of 2/8/2010 does not have a nice, simple, conversion process that will take a file in the many different formats out there and drop it into a nicely formatted .flv file for easy slideshowpro (or other flash based package) streaming.

The alternative, that I have most often seen, is using ffMpeg to convert source video into .flv format. Unfortunately, this process can a bit arcane. While there are other libraries out there that wrap up ffMpeg with a nice shiny, albeit complex, bow. I figured there might be some use for a simple c# library that does a couple simple, but very useful processes.

The following class will convert your input file to a .flv file and create a preview image from 1/3 of the way into the movie. By getting the preview image from 1/3 into the movie, we can avoid a completely black preview image that can come from a video that fades in.

Getting Started:

Create a directory in your project that contains the ffMpeg.exe file, this file will be referenced by the class below. This class is also going to use the web.config or app.config to store the location of our ffMpeg.exe file and a couple key settings. To do this, you will need to import system.configuration into your project and include the following line:

	using System.Configuration;

To start with, we have a couple properties that expose the working path that ffMpeg will need while it is processing our video file along with a property that exposes the location of our exe file.

	private string _ffExe;
	public string ffExe
	{
		get
		{
			return _ffExe;
		}
		set
		{
			_ffExe = value;
		}
	}

	private string _WorkingPath;
	public string WorkingPath
	{
		get
		{
			return _WorkingPath;
		}
		set
		{
			_WorkingPath = value;
		}
	}

In our constructors, we will call an initialize method that will attempt to grab our exepath from web.config, assuming that one has not been entered into our second constructor.

Note: In this example, the class is name “Converter”

	public Converter()
	{
		Initialize();
	}
	public Converter(string ffmpegExePath)
	{
		_ffExe = ffmpegExePath;
		Initialize();
	}

Initialization

You will note that the we are testing to see if the ffmpeg.exe file location exists before attempting to pull it from web.config.

	//Make sure we have valid ffMpeg.exe file and working directory to do our dirty work.
	private void Initialize()
	{
		//first make sure we have a value for the ffexe file setting
		if (string.IsNullOrEmpty(_ffExe))
		{
			object o = ConfigurationManager.AppSettings["ffmpeg:ExeLocation"];
			if (o == null)
			{
				throw new Exception("Could not find the location of the ffmpeg exe file.  The path for ffmpeg.exe " +
				"can be passed in via a constructor of the ffmpeg class (this class) or by setting in the app.config or web.config file.  " +
				"in the appsettings section, the correct property name is: ffmpeg:ExeLocation");
			}
			else
			{
				if (string.IsNullOrEmpty(o.ToString()))
				{
					throw new Exception("No value was found in the app setting for ffmpeg:ExeLocation");
				}
				_ffExe = o.ToString();
			}
		}

		//Now see if ffmpeg.exe exists
		string workingpath = GetWorkingFile();
		if (string.IsNullOrEmpty(workingpath))
		{
			//ffmpeg doesn't exist at the location stated.
			throw new Exception("Could not find a copy of ffmpeg.exe");
		}
		_ffExe = workingpath;

		//now see if we have a temporary place to work
		if (string.IsNullOrEmpty(_WorkingPath))
		{
			object o = ConfigurationManager.AppSettings["ffmpeg:WorkingPath"];
			if (o != null)
			{
				_WorkingPath = o.ToString();
			}
			else
			{
				_WorkingPath = string.Empty;
			}
		}
	}

	private string GetWorkingFile()
	{
		//try the stated directory
		if (File.Exists(_ffExe))
		{
			return _ffExe;
		}

		//oops, that didn't work, try the base directory
		if (File.Exists(Path.GetFileName(_ffExe)))
		{
			return Path.GetFileName(_ffExe);
		}

		//well, now we are really unlucky, let's just return null
		return null;
	}

Loading Files Without Creating Locks

These subs might be a bit out of place but are useful as they create our memory resident objects without throwing a lock on the source file. This means that we can run more than one process at once, or delete our file without screwing things up for another process.

	public static System.Drawing.Image LoadImageFromFile(string fileName)
	{
		System.Drawing.Image theImage = null;
		using (FileStream fileStream = new FileStream(fileName, FileMode.Open,
		FileAccess.Read))
		{
			byte[] img;
			img = new byte[fileStream.Length];
			fileStream.Read(img, 0, img.Length);
			fileStream.Close();
			theImage = System.Drawing.Image.FromStream(new MemoryStream(img));
			img = null;
		}
		GC.Collect();
		return theImage;
	}

	public static MemoryStream LoadMemoryStreamFromFile(string fileName)
	{
		MemoryStream ms = null;
		using (FileStream fileStream = new FileStream(fileName, FileMode.Open,
		FileAccess.Read))
		{
			byte[] fil;
			fil = new byte[fileStream.Length];
			fileStream.Read(fil, 0, fil.Length);
			fileStream.Close();
			ms = new MemoryStream(fil);
		}
		GC.Collect();
		return ms;
	}

Running the ffMpeg Process

Now that we have setup our class and have some basic helper subs to get us going, we need to actually have a method that will run the ffMpeg process.


	//Note the private call here and the argument for Parameters.  The private call is
	//being made here because, in this class, we don't really want to have this method
	//called from outside of the class -- this, however flies in the face of allowing the
	//parameters argument (why not just allow out the public call so that a developer can
	//put in the parameters from their own code?  I guess one could do it and it would probably
	//work fine but, for this implementation, I chose to leave it private.
	private string RunProcess(string Parameters)
	{
		//create a process info object so we can run our app
		ProcessStartInfo oInfo = new ProcessStartInfo(this._ffExe, Parameters);
		oInfo.UseShellExecute = false;
		oInfo.CreateNoWindow = true;

		//so we are going to redirect the output and error so that we can parse the return
		oInfo.RedirectStandardOutput = true;
		oInfo.RedirectStandardError = true;

		//Create the output and streamreader to get the output
		string output = null; StreamReader srOutput = null;

		//try the process
		try
		{
			//run the process
			Process proc = System.Diagnostics.Process.Start(oInfo);

			proc.WaitForExit();

			//get the output
			srOutput = proc.StandardError;

			//now put it in a string
			output = srOutput.ReadToEnd();

			proc.Close();
		}
		catch (Exception)
		{
			output = string.Empty;
		}
		finally
		{
			//now, if we succeded, close out the streamreader
			if (srOutput != null)
			{
				srOutput.Close();
				srOutput.Dispose();
			}
		}
		return output;
	}

Now let’s make some functional stuff

Now that we have called the ffMpeg process, we need to get some video info, get a video file, and a preview image. So, with that being said, onto more source code.

Getting the Details

So, we need to now parse the details of our ffMpeg.exe output and read some details about the video file.

	//We are going to take in memory stream for this file to allow for different input options.
	//Unfortunately, this means that we also need the file extension to pass it out to ffMpeg.
	public VideoFile GetVideoInfo(MemoryStream inputFile, string Filename)
	{
		//Create a temporary file for our use in ffMpeg
		string tempfile = Path.Combine(this.WorkingPath, System.Guid.NewGuid().ToString() + Path.GetExtension(Filename));
		FileStream fs = File.Create(tempfile);

		//write the memory stream to a file and close our the stream so it can be used again.
		inputFile.WriteTo(fs);
		fs.Flush();
		fs.Close();
		GC.Collect();

		//Video File is a class you will see further down this post.  It has some basic information about the video
		VideoFile vf = null;
		try
		{
			vf = new VideoFile(tempfile);
		}
		catch (Exception ex)
		{
			throw ex;
		}

		//And, without adieu, a call to our main method for this functionality.
		GetVideoInfo(vf);

		try
		{
			File.Delete(tempfile);
		}
		catch (Exception)
		{

		}

		return vf;
	}

	//This sub is just another overload to allow input of a direct path, we are just
	//using the videofile class to send in.  More on the video file class further down
	//the article.
	public VideoFile GetVideoInfo(string inputPath)
	{
		VideoFile vf = null;
		try
		{
			vf = new VideoFile(inputPath);
		}
		catch (Exception ex)
		{
			throw ex;
		}
		GetVideoInfo(vf);
		return vf;
	}

	//And now the important code for the GetVideoInfo
	public void GetVideoInfo(VideoFile input)
	{
		//set up the parameters for video info -- these will be passed into ffMpeg.exe
		string Params = string.Format("-i {0}", input.Path);
		string output = RunProcess(Params);
		input.RawInfo = output;

		//Use a regular expression to get the different properties from the video parsed out.
		Regex re = new Regex("[D|d]uration:.((\\d|:|\\.)*)");
		Match m = re.Match(input.RawInfo);

		if (m.Success)
		{
			string duration = m.Groups[1].Value;
			string[] timepieces = duration.Split(new char[] { ':', '.' });
			if (timepieces.Length == 4)
			{
				input.Duration = new TimeSpan(0, Convert.ToInt16(timepieces[0]), Convert.ToInt16(timepieces[1]), Convert.ToInt16(timepieces[2]), Convert.ToInt16(timepieces[3]));
			}
		}

		//get audio bit rate
		re = new Regex("[B|b]itrate:.((\\d|:)*)");
		m = re.Match(input.RawInfo);
		double kb = 0.0;
		if (m.Success)
		{
			Double.TryParse(m.Groups[1].Value, out kb);
		}
		input.BitRate = kb;

		//get the audio format
		re = new Regex("[A|a]udio:.*");
		m = re.Match(input.RawInfo);
		if (m.Success)
		{
			input.AudioFormat = m.Value;
		}

		//get the video format
		re = new Regex("[V|v]ideo:.*");
		m = re.Match(input.RawInfo);
		if (m.Success)
		{
			input.VideoFormat = m.Value;
		}

		//get the video format
		re = new Regex("(\\d{2,3})x(\\d{2,3})");
		m = re.Match(input.RawInfo);
		if (m.Success)
		{
			int width = 0; int height = 0;
			int.TryParse(m.Groups[1].Value, out width);
			int.TryParse(m.Groups[2].Value, out height);
			input.Width = width;
			input.Height = height;
		}
		input.infoGathered = true;
	}

Finally, do the conversion

So, here is the conversion meat and preview imaging.

	//Note the ouputpackage object output.  The output package class is detailed below.
	//this overload does much the same as the one above does, in that, it offers the ability
	//to input a memory stream vs. a filename or our videofile input class.
	public OutputPackage ConvertToFLV(MemoryStream inputFile, string Filename)
	{
		string tempfile = Path.Combine(this.WorkingPath, System.Guid.NewGuid().ToString() + Path.GetExtension(Filename));
		FileStream fs = File.Create(tempfile);
		inputFile.WriteTo(fs);
		fs.Flush();
		fs.Close();
		GC.Collect();

		VideoFile vf = null;
		try
		{
			vf = new VideoFile(tempfile);
		}
		catch (Exception ex)
		{
			throw ex;
		}

		OutputPackage oo = ConvertToFLV(vf);

		try{
			File.Delete(tempfile);
		} catch(Exception) {

		}

		return oo;
	}
	public OutputPackage ConvertToFLV(string inputPath)
	{
		VideoFile vf = null;
		try
		{
			vf = new VideoFile(inputPath);
		}
		catch (Exception ex)
		{
			throw ex;
		}

		OutputPackage oo = ConvertToFLV(vf);
		return oo;
	}

	//The actually important code, rather than an overload.
	public OutputPackage ConvertToFLV(VideoFile input)
	{
		//check to see if we have already gathered our info so we know
		//where to get our preview image from.
		if (!input.infoGathered)
		{
			GetVideoInfo(input);
		}

		//Create our output object
		OutputPackage ou = new OutputPackage();

		//set up the parameters for getting a previewimage
		string filename = System.Guid.NewGuid().ToString() + ".jpg";
		int secs;

		//divide the duration in 3 to get a preview image in the middle of the clip
		//instead of a black image from the beginning.
		secs = (int)Math.Round(TimeSpan.FromTicks(input.Duration.Ticks / 3).TotalSeconds, 0);

		string finalpath = Path.Combine(this.WorkingPath, filename);

		//These are the parameters for setting up a preview image that must be passed to ffmpeg.
		//Note that we are asking for a jpeg image at our specified seconds.
		string Params = string.Format("-i {0} {1} -vcodec mjpeg -ss {2} -vframes 1 -an -f rawvideo", input.Path, finalpath, secs);
		string output = RunProcess(Params);

		ou.RawOutput = output;

		//Ok, so hopefully we now have a preview file.  If the file
		//did not get created properly, try again at the first frame.
		if (File.Exists(finalpath))
		{
			//load that file into our output package and attempt to delete the file
			//since we no longer need it.
			ou.PreviewImage = LoadImageFromFile(finalpath);
			try
			{
				File.Delete(finalpath);
			}
			catch (Exception) { }
		} else { //try running again at frame 1 to get something
			Params = string.Format("-i {0} {1} -vcodec mjpeg -ss {2} -vframes 1 -an -f rawvideo", input.Path, finalpath, 1);
			output = RunProcess(Params);

			ou.RawOutput = output;

			if (File.Exists(finalpath)) {
				ou.PreviewImage = LoadImageFromFile(finalpath);
				try
				{
					File.Delete(finalpath);
				}
				catch (Exception) { }
			}
		}

		finalpath = Path.Combine(this.WorkingPath, filename);
		filename = System.Guid.NewGuid().ToString() + ".flv";

		//Now we are going to actually create the converted file.  Note that we are asking for
		//a video at 22khz 64bit.  This can be changed by a couple quick alterations to this line,
		//or by extending out this class to offer multiple different conversions.
		Params = string.Format("-i {0} -y -ar 22050 -ab 64 -f flv {1}", input.Path, finalpath);
		output = RunProcess(Params);

		//Check to see if our conversion file exists and then load the converted
		//file into our output package.  If the file does exist and we are able to
		//load it into our output package, we can delete the work file.
		if (File.Exists(finalpath))
		{
			ou.VideoStream = LoadMemoryStreamFromFile(finalpath);
			try
			{
				File.Delete(finalpath);
			}
			catch (Exception) { }
		}
		return ou;
	}

Supplementary Classes

Throughout this article, you will have noticed the use of “VideoFile” and “OutputPackage”. These classes are just informational classes that provide simple ways of accessing everything.
Here they are:

	public class VideoFile
	{
		#region Properties
		private string _Path;
		public string Path
		{
			get
			{
				return _Path;
			}
			set
			{
				_Path = value;
			}
		}

		public TimeSpan Duration { get; set; }
		public double BitRate { get; set; }
		public string AudioFormat { get; set; }
		public string VideoFormat { get; set; }
		public int Height { get; set; }
		public int Width { get; set; }
		public string RawInfo { get; set; }
		public bool infoGathered {get; set;}
		#endregion

		#region Constructors
		public VideoFile(string path)
		{
			_Path = path;
			Initialize();
		}
		#endregion

		#region Initialization
		private void Initialize()
		{
			this.infoGathered = false;
			//first make sure we have a value for the video file setting
			if (string.IsNullOrEmpty(_Path))
			{
				throw new Exception("Could not find the location of the video file");
			}

			//Now see if the video file exists
			if (!File.Exists(_Path))
			{
				throw new Exception("The video file " + _Path + " does not exist.");
			}
		}
		#endregion
	}

	public class OutputPackage
	{
		public MemoryStream VideoStream { get; set; }
		public System.Drawing.Image PreviewImage { get; set; }
		public string RawOutput { get; set; }
		public bool Success { get; set; }
	}

Full Code for the class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Diagnostics;
using System.Configuration;
using System.Text.RegularExpressions;

namespace ffMpeg
{
	public class Converter
	{
		#region Properties
		private string _ffExe;
		public string ffExe
		{
			get
			{
				return _ffExe;
			}
			set
			{
				_ffExe = value;
			}
		}

		private string _WorkingPath;
		public string WorkingPath
		{
			get
			{
				return _WorkingPath;
			}
			set
			{
				_WorkingPath = value;
			}
		}

		#endregion

		#region Constructors
		public Converter()
		{
			Initialize();
		}
		public Converter(string ffmpegExePath)
		{
			_ffExe = ffmpegExePath;
			Initialize();
		}
		#endregion

		#region Initialization
		private void Initialize()
		{
			//first make sure we have a value for the ffexe file setting
			if (string.IsNullOrEmpty(_ffExe))
			{
				object o = ConfigurationManager.AppSettings["ffmpeg:ExeLocation"];
				if (o == null)
				{
					throw new Exception("Could not find the location of the ffmpeg exe file.  The path for ffmpeg.exe " +
					"can be passed in via a constructor of the ffmpeg class (this class) or by setting in the app.config or web.config file.  " +
					"in the appsettings section, the correct property name is: ffmpeg:ExeLocation");
				}
				else
				{
					if (string.IsNullOrEmpty(o.ToString()))
					{
						throw new Exception("No value was found in the app setting for ffmpeg:ExeLocation");
					}
					_ffExe = o.ToString();
				}
			}

			//Now see if ffmpeg.exe exists
			string workingpath = GetWorkingFile();
			if (string.IsNullOrEmpty(workingpath))
			{
				//ffmpeg doesn't exist at the location stated.
				throw new Exception("Could not find a copy of ffmpeg.exe");
			}
			_ffExe = workingpath;

			//now see if we have a temporary place to work
			if (string.IsNullOrEmpty(_WorkingPath))
			{
				object o = ConfigurationManager.AppSettings["ffmpeg:WorkingPath"];
				if (o != null)
				{
					_WorkingPath = o.ToString();
				}
				else
				{
					_WorkingPath = string.Empty;
				}
			}
		}

		private string GetWorkingFile()
		{
			//try the stated directory
			if (File.Exists(_ffExe))
			{
				return _ffExe;
			}

			//oops, that didn't work, try the base directory
			if (File.Exists(Path.GetFileName(_ffExe)))
			{
				return Path.GetFileName(_ffExe);
			}

			//well, now we are really unlucky, let's just return null
			return null;
		}
		#endregion

		#region Get the File without creating a file lock
		public static System.Drawing.Image LoadImageFromFile(string fileName)
		{
			System.Drawing.Image theImage = null;
			using (FileStream fileStream = new FileStream(fileName, FileMode.Open,
			FileAccess.Read))
			{
				byte[] img;
				img = new byte[fileStream.Length];
				fileStream.Read(img, 0, img.Length);
				fileStream.Close();
				theImage = System.Drawing.Image.FromStream(new MemoryStream(img));
				img = null;
			}
			GC.Collect();
			return theImage;
		}

		public static MemoryStream LoadMemoryStreamFromFile(string fileName)
		{
			MemoryStream ms = null;
			using (FileStream fileStream = new FileStream(fileName, FileMode.Open,
			FileAccess.Read))
			{
				byte[] fil;
				fil = new byte[fileStream.Length];
				fileStream.Read(fil, 0, fil.Length);
				fileStream.Close();
				ms = new MemoryStream(fil);
			}
			GC.Collect();
			return ms;
		}
		#endregion

		#region Run the process
		private string RunProcess(string Parameters)
		{
			//create a process info
			ProcessStartInfo oInfo = new ProcessStartInfo(this._ffExe, Parameters);
			oInfo.UseShellExecute = false;
			oInfo.CreateNoWindow = true;
			oInfo.RedirectStandardOutput = true;
			oInfo.RedirectStandardError = true;

			//Create the output and streamreader to get the output
			string output = null; StreamReader srOutput = null;

			//try the process
			try
			{
				//run the process
				Process proc = System.Diagnostics.Process.Start(oInfo);

				proc.WaitForExit();

				//get the output
				srOutput = proc.StandardError;

				//now put it in a string
				output = srOutput.ReadToEnd();

				proc.Close();
			}
			catch (Exception)
			{
				output = string.Empty;
			}
			finally
			{
				//now, if we succeded, close out the streamreader
				if (srOutput != null)
				{
					srOutput.Close();
					srOutput.Dispose();
				}
			}
			return output;
		}
		#endregion

		#region GetVideoInfo
		public VideoFile GetVideoInfo(MemoryStream inputFile, string Filename)
		{
			string tempfile = Path.Combine(this.WorkingPath, System.Guid.NewGuid().ToString() + Path.GetExtension(Filename));
			FileStream fs = File.Create(tempfile);
			inputFile.WriteTo(fs);
			fs.Flush();
			fs.Close();
			GC.Collect();

			VideoFile vf = null;
			try
			{
				vf = new VideoFile(tempfile);
			}
			catch (Exception ex)
			{
				throw ex;
			}

			GetVideoInfo(vf);

			try
			{
				File.Delete(tempfile);
			}
			catch (Exception)
			{

			}

			return vf;
		}
		public VideoFile GetVideoInfo(string inputPath)
		{
			VideoFile vf = null;
			try
			{
				vf = new VideoFile(inputPath);
			}
			catch (Exception ex)
			{
				throw ex;
			}
			GetVideoInfo(vf);
			return vf;
		}
		public void GetVideoInfo(VideoFile input)
		{
			//set up the parameters for video info
			string Params = string.Format("-i {0}", input.Path);
			string output = RunProcess(Params);
			input.RawInfo = output;

			//get duration
			Regex re = new Regex("[D|d]uration:.((\\d|:|\\.)*)");
			Match m = re.Match(input.RawInfo);

			if (m.Success)
			{
				string duration = m.Groups[1].Value;
				string[] timepieces = duration.Split(new char[] { ':', '.' });
				if (timepieces.Length == 4)
				{
					input.Duration = new TimeSpan(0, Convert.ToInt16(timepieces[0]), Convert.ToInt16(timepieces[1]), Convert.ToInt16(timepieces[2]), Convert.ToInt16(timepieces[3]));
				}
			}

			//get audio bit rate
			re = new Regex("[B|b]itrate:.((\\d|:)*)");
			m = re.Match(input.RawInfo);
			double kb = 0.0;
			if (m.Success)
			{
				Double.TryParse(m.Groups[1].Value, out kb);
			}
			input.BitRate = kb;

			//get the audio format
			re = new Regex("[A|a]udio:.*");
			m = re.Match(input.RawInfo);
			if (m.Success)
			{
				input.AudioFormat = m.Value;
			}

			//get the video format
			re = new Regex("[V|v]ideo:.*");
			m = re.Match(input.RawInfo);
			if (m.Success)
			{
				input.VideoFormat = m.Value;
			}

			//get the video format
			re = new Regex("(\\d{2,3})x(\\d{2,3})");
			m = re.Match(input.RawInfo);
			if (m.Success)
			{
				int width = 0; int height = 0;
				int.TryParse(m.Groups[1].Value, out width);
				int.TryParse(m.Groups[2].Value, out height);
				input.Width = width;
				input.Height = height;
			}
			input.infoGathered = true;
		}
		#endregion

		#region Convert to FLV
		public OutputPackage ConvertToFLV(MemoryStream inputFile, string Filename)
		{
			string tempfile = Path.Combine(this.WorkingPath, System.Guid.NewGuid().ToString() + Path.GetExtension(Filename));
			FileStream fs = File.Create(tempfile);
			inputFile.WriteTo(fs);
			fs.Flush();
			fs.Close();
			GC.Collect();

			VideoFile vf = null;
			try
			{
				vf = new VideoFile(tempfile);
			}
			catch (Exception ex)
			{
				throw ex;
			}

			OutputPackage oo = ConvertToFLV(vf);

			try{
				File.Delete(tempfile);
			} catch(Exception) {

			}

			return oo;
		}
		public OutputPackage ConvertToFLV(string inputPath)
		{
			VideoFile vf = null;
			try
			{
				vf = new VideoFile(inputPath);
			}
			catch (Exception ex)
			{
				throw ex;
			}

			OutputPackage oo = ConvertToFLV(vf);
			return oo;
		}
		public OutputPackage ConvertToFLV(VideoFile input)
		{
			if (!input.infoGathered)
			{
				GetVideoInfo(input);
			}
			OutputPackage ou = new OutputPackage();

			//set up the parameters for getting a previewimage
			string filename = System.Guid.NewGuid().ToString() + ".jpg";
			int secs;

			//divide the duration in 3 to get a preview image in the middle of the clip
			//instead of a black image from the beginning.
			secs = (int)Math.Round(TimeSpan.FromTicks(input.Duration.Ticks / 3).TotalSeconds, 0);

			string finalpath = Path.Combine(this.WorkingPath, filename);
			string Params = string.Format("-i {0} {1} -vcodec mjpeg -ss {2} -vframes 1 -an -f rawvideo", input.Path, finalpath, secs);
			string output = RunProcess(Params);

			ou.RawOutput = output;

			if (File.Exists(finalpath))
			{
				ou.PreviewImage = LoadImageFromFile(finalpath);
				try
				{
					File.Delete(finalpath);
				}
				catch (Exception) { }
			} else { //try running again at frame 1 to get something
				Params = string.Format("-i {0} {1} -vcodec mjpeg -ss {2} -vframes 1 -an -f rawvideo", input.Path, finalpath, 1);
				output = RunProcess(Params);

				ou.RawOutput = output;

				if (File.Exists(finalpath)) {
					ou.PreviewImage = LoadImageFromFile(finalpath);
					try
					{
						File.Delete(finalpath);
					}
					catch (Exception) { }
				}
			}

			finalpath = Path.Combine(this.WorkingPath, filename);
			filename = System.Guid.NewGuid().ToString() + ".flv";
			Params = string.Format("-i {0} -y -ar 22050 -ab 64 -f flv {1}", input.Path, finalpath);
			output = RunProcess(Params);

			if (File.Exists(finalpath))
			{
				ou.VideoStream = LoadMemoryStreamFromFile(finalpath);
				try
				{
					File.Delete(finalpath);
				}
				catch (Exception) { }
			}
			return ou;
		}
		#endregion
	}

	public class VideoFile
	{
		#region Properties
		private string _Path;
		public string Path
		{
			get
			{
				return _Path;
			}
			set
			{
				_Path = value;
			}
		}

		public TimeSpan Duration { get; set; }
		public double BitRate { get; set; }
		public string AudioFormat { get; set; }
		public string VideoFormat { get; set; }
		public int Height { get; set; }
		public int Width { get; set; }
		public string RawInfo { get; set; }
		public bool infoGathered {get; set;}
		#endregion

		#region Constructors
		public VideoFile(string path)
		{
			_Path = path;
			Initialize();
		}
		#endregion

		#region Initialization
		private void Initialize()
		{
			this.infoGathered = false;
			//first make sure we have a value for the video file setting
			if (string.IsNullOrEmpty(_Path))
			{
				throw new Exception("Could not find the location of the video file");
			}

			//Now see if the video file exists
			if (!File.Exists(_Path))
			{
				throw new Exception("The video file " + _Path + " does not exist.");
			}
		}
		#endregion
	}

	public class OutputPackage
	{
		public MemoryStream VideoStream { get; set; }
		public System.Drawing.Image PreviewImage { get; set; }
		public string RawOutput { get; set; }
		public bool Success { get; set; }
	}
}