Today there is again a bit of C# code. I’m writing about how you can create video files in C # from individual images or bitmaps. Using the AForge library, which I have used in the already in the C# webcam tutorial, this is going to be relatively simple.
Preparations
For the following tutorial you need the AForge.Video.FFMPEG.dll library and its FFMPEG libraries. Both can be found by clicking the below link. On the downloadpage you have to select that .zip-file, which contains “(libs only)” in it’s filename.
Now open your Visual Studio or an alternative program, that you want to use to write your program. (For the following tutorial I’m using Visual Studio.)
Create a project
Next you create a new project, I decided on a WinForms project, and wait until the Visual Studio has arranged everything. Unpack the previously downloaded AForge archive. In the release folder of the archive you will find all AForge libraries. However, for this tutorial, we only need the AForge.Video.FFMPEG library. Copy this into the folder which contains your Visual Studio project. Now add a reference the AForge.Video.FFMPEG library. (If you don’t know how to add references, have a look at this short article.)
Before we go on, two other settings need to be made to your project. One the one hand you have to adjust the .NET framework target version. This must not exceed version 3.5, because the AForge libs we’re using aren’t compatible with .NET 4.0 & .NET 4.5. This changes can be made in the properties of your project. (See left-hand screenshot)
On the other hand you may have to change the target architecture of your project. By default this should be set to “Any CPU”. Here you have to explicitly specify x86 as target architecture. You can also make this setting on the properties page of your project. (See right-hand screenshot)
Short status report – you should have created a project, added a reference to the AForge.Video.FFMPEG library, set the target platform to x86 and the target framework version to 3.5 or lower now. If so, it can go on.
No products found.
In the next step, we need a few more dlls from the AForge archive. You can find these in the folder “Externals\ffmpeg” inside the AForge archive. All files in this folder have to be copied to the output folder of your Visual Studio project. (After we changed the target architecture this now should be “YourProjectFolder\bin\x86\Debug”.)Beginning with the code
If you’ve also done this, we can start with the code. The first thing what you should do is to integrate the AForge library by writing the using directive.
using AForge.Video.FFMPEG;
In the next step we create a method in which want to write the C# code for video creation. For this reason I have created a button on the application’s main form and will subsequently use the button’s click method. (I know that this isn’t the perfect way, but it’s a good way to create a simple skeleton for the substantial code of this tutorial – the C# video writer code.)
private void buttonCreateVideo_Click(object sender, EventArgs e) { }
Create VideoFileWriter
Note: From now on all the following code snippets belong to this method. I will develop and explain the code step by step. Those, who only look for the solution, should now scroll to the end of this article.
First, we create two variables for the width and height of the video. We hereby specify the resolution of the video. Then we create an instance of the VideoFileWriter class and open a new video file using the open()-method.
int width = 640; int height = 480; VideoFileWriter writer = new VideoFileWriter(); writer.Open("en.code-bude_test_video.avi", width, height, 25, VideoCodec.MPEG4, 1000000);
A brief explanation of the open()-method. The fourth parameter specifies the frames per second of the video, the fifth specifies the videocodec and the sixth defines the bitrate of the video. The mentioned rate of 1000000 corresponds to a video bitrate of 1 Mbps. The higher the bitrate, the larger the video and the better the quality.
Writing the frames
Now we can arbitrarily write as many frames (in the form of bitmap graphics) as we like. That’s what the following code snippet does. By use of the modulus operator (%), and the random number generator, we will create different frames which will result in a nice animation. Thanks to the frame rate of 25 FPS, which we have stated above when we set up the open()-method, we know that 25 graphics result in 1 second of video. Since we are creating 375 bitmaps (frames) below, our video will be 15 seconds in length.
Bitmap image = new Bitmap(width, height); Graphics g = Graphics.FromImage(image); g.FillRectangle(Brushes.Black, 0, 0, width, height); Brush[] brushList = new Brush[] { Brushes.Green, Brushes.Red, Brushes.Yellow, Brushes.Pink, Brushes.LimeGreen }; Random rnd = new Random(); for (int i = 0; i < 250; i++) { int rndTmp = rnd.Next(1, 3); Application.DoEvents(); g.FillRectangle(brushList[i%5], (i % width)*2, (i % height) * 0.5f, i%30, i%30); g.FillRectangle(brushList[i % 5], (i % width)*2, (i % height)*2, i % 30, i % 30); g.FillRectangle(brushList[i % 5], (i % width) * 0.5f, (i % height) *2, i % 30, i % 30); g.Save(); writer.WriteVideoFrame(image); } g.DrawString("(c) 2013 by code-bude.net", new System.Drawing.Font("Calibri", 30), Brushes.White, 80, 240); g.Save(); for (int i = 0; i < 125; i++) { writer.WriteVideoFrame(image); }
Save the video file
In the last step we have to close the VideoFileWriter yet.
writer.Close();
That’s it. The few lines of code shown in this article are completely enough to create your very own video by using C#.
Download and overview
In the below listing there is once again the complete code of my project’s Form1.cs file. If you want you can also download the whole Visual Studio solution by clicking on the following link.
Download: VideoFileWriter solution
using AForge.Video.FFMPEG; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace VideoWriter { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void buttonCreateVideo_Click(object sender, EventArgs e) { int width = 640; int height = 480; VideoFileWriter writer = new VideoFileWriter(); writer.Open("code-bude_test_video.avi", width, height, 25, VideoCodec.MPEG4, 1000000); Bitmap image = new Bitmap(width, height); Graphics g = Graphics.FromImage(image); g.FillRectangle(Brushes.Black, 0, 0, width, height); Brush[] brushList = new Brush[] { Brushes.Green, Brushes.Red, Brushes.Yellow, Brushes.Pink, Brushes.LimeGreen }; Random rnd = new Random(); for (int i = 0; i < 250; i++) { int rndTmp = rnd.Next(1, 3); Application.DoEvents(); g.FillRectangle(brushList[i%5], (i % width)*2, (i % height) * 0.5f, i%30, i%30); g.FillRectangle(brushList[i % 5], (i % width)*2, (i % height)*2, i % 30, i % 30); g.FillRectangle(brushList[i % 5], (i % width) * 0.5f, (i % height) *2, i % 30, i % 30); g.Save(); writer.WriteVideoFrame(image); } g.DrawString("(c) 2013 by code-bude.net", new System.Drawing.Font("Calibri", 30), Brushes.White, 80, 240); g.Save(); for (int i = 0; i < 125; i++) { writer.WriteVideoFrame(image); } writer.Close(); } } }
I am genuinely thankful to the owner of this website for sharing his brilliant ideas. I can see how much you’ve helped everybody who comes across your page. By the way, here is my webpage FQ6 about Marketing.
It is always great to come across a page where the admin take an actual effort to generate a really good article. Check out my website ArticleHome concerning about Website Traffic.
I like how well-written and informative your content is. You have actually given us, your readers, brilliant information and not just filled up your blog with flowery texts like many blogs today do. If you visit my website Seoranko about Search Engine Optimization, I’m sure you can also find something for yourself.
I like how well-written and informative your content is. You have actually given us, your readers, brilliant information and not just filled up your blog with flowery texts like many blogs today do. If you visit my website Webemail24 about Data Mining, I’m sure you can also find something for yourself.
does it work in unity 3D webGL?
Your work is awesome sir ,
but I have a query I am creating a video from set of images but video is playing very fast I want at least 5 seconds for each image in video , I have tried using timeSpan but I didn’t get desired result
could you please suggest me or help me to find out my solution .
here is my code
string basePaths = @”C:\Users\sidsi\OneDrive\Desktop\pictures”;
TimeSpan timeSpan = new TimeSpan(0, 0, 5);
string[] paths = Directory.GetFiles(basePaths);
int imagesCount = paths.Length;
using (var vFWriter = new VideoFileWriter())
{
vFWriter.Open(@”D:\videosss.avi”, 1920, 1080,15,VideoCodec.MPEG4,4000000);
for (int i = 0; i < imagesCount; i++)
{
var imagePath = string.Format(paths[i]);
using (Bitmap image = Bitmap.FromFile(imagePath) as Bitmap)
{
vFWriter.WriteVideoFrame(image,timeSpan);
}
}
}
}
thanks .
Hi..
I can not use both at the same time.
Project x86 v3,5
Error : Additional information: The specified module could not be found. (Exception from HRESULT: 0x8007007E)
AForge.Video.DirectShow;
AForge.Video.FFMPEG;
Code :
VideoCaptureDevice videoSource;
private void Form1_Load(object sender, EventArgs e)
{
VideoFileWriter writer = new VideoFileWriter();
writer.Open(“FinalVideo.avi”, 50, 50, 24, VideoCodec.MPEG4, 1000000);
}
Thanks. So complete and helpful. Works just fine. But is the AFORGE.NET no longer developed. Latest versions for x86 and .NET 2.2.5 ?
i am using AForge.Video.FFMPEG.dll and this dll only somw few codec so i use some other codec like cinapak so how to implement or use in my project..
hello sir,
I am using Your code and i change VideoCodec.ffdshow so how to change in program or .dll file.
For Example :
writer.Open(“C:\\Users\\demo.avi”, width, height, 30, VideoCodec.Raw, 943718000);
VideoCodec.Raw Replace withe VideoCodec.ffdshadow
this error are generate in code.
Could not load file or assembly ‘AForge.Video.FFMPEG, Version=2.2.4.0, Culture=neutral, PublicKeyToken=03563089b1be05dd’ or one of its dependencies. An attempt was made to load a program with an incorrect format.
what will be the solution of the code.
Seems like you haven’t referenced the correct AForge library.
thank you raffi…
working a code.
This is due to you are using 64 bit operating system. but it works only in 32 bit OS.
Hey Raffi,
I am trying to use AForge.Video.FFMPEG.dll but getting following error:
“An unhandled exception of type ‘System.BadImageFormatException’ occurred in Microsoft.VisualStudio.HostingProcess.Utilities.dll
Additional information: Could not load file or assembly ‘AForge.Video.FFMPEG, Version=2.2.5.0, Culture=neutral, PublicKeyToken=03563089b1be05dd’ or one of its dependencies. An attempt was made to load a program with an incorrect format.”
I am using .Net framework 4.0 and can’t change to any other version.
Here is my code:
using AForge.Video.FFMPEG;
namespace AForge.Video.FFMPEG.Demo
{
class Program
{
static void Main(string[] args)
{
using (var videoFileWriter = new VideoFileWriter())
{
}
}
}
}
Please help me out as I need it badly.
Thanks,
Rajiv
hi..
u solve the problem or not..
same problem me..
plz if you solve the problem give a reason and help..
hi sir,
i write code in c# to capture video from webcam and saved image in bmp by using DShowNET library. it’s working now i want to save preview video into avi file with start,stop buttons i tried but not working.
If you know how to fix this assist me to solve this issue.
pls…………………………………reply me it’s very urjent.
thanks advance for reply.
email – hariniroddam@gmail.com
i want use it to record screen in unity3d ,can i use these solution on mobile platform?
I’m sorry, but I can’t answer because I’ve never tried it. But have you checked already if there’s a AForge Lib für mobile devices at all?
I haven’t checked, thank you, I think the other way~~
I keep on getting an error saying “server execution failed” when I try to open it in Windows Media Player but it works fine in VLC Media player. This isn’t a big problem but it would be appreciated if someone could explain why this happens and/or give me a solution to this dilemma.
Dear Raffi
Well job. great work.
I use win form application c++ programming in VS2012. On my win form, I have three buttons that used for staring camera, stopping camera and saving film. I finished starting and stopping camera now and I would like to record the captured film on webcam and save it to specified path on my PC.
Please help me for recording camera using c++ in windows form application.
private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e)
{
}
my email is jamali.tabrizu@yahoo.com
Hey Raffi,
thanks for this help but i want to create web application like u do that i get uploaded images and i want to make a video streaming from them but i failed and this is my code . please help me in this and thanks in advance . this is my code
int width = 320;
int height = 240;
VideoFileWriter writer = new VideoFileWriter();
writer.Open(“code-bude_test_video.avi”, width, height, 200, VideoCodec.MPEG4, 1000000);
Bitmap img = new Bitmap(320,240 );
//var cubit = new AForge.Imaging.Filters.ResizeBilinear(320, 240);
string[] files = Directory.GetFiles(Server.MapPath(“~/pics/”));
int index = 0;
int failed = 0;
foreach (var item in files)
{
index++;
try
{
//System.Drawing.Image img = System.Drawing.Image.FromFile(item) as Bitmap;
// image = cubit.Apply(image);
for (int i = 0; i < 62; i++)
{
img = System.Drawing.Image.FromFile(item) as Bitmap;
writer.WriteVideoFrame(img);
}
}
catch
{
failed++;
}
Response.Write(index + " of " + files.Length + ". Failed: " + failed);
}
writer.Close();
i don't know what is the error . that when i compiled it it tell me that all of images failed
Hi Raffi, great code, thanks!
We are currently using a modifed AviWriter.cs in our open-source screenshot/screencast application ShareX. We write a collection of images to avi container. Using x264VfW we create a H264 compliant stream however because it is in an avi container, we then have to mux it to mp4 container using ffmpeg. Therefore it is a two-step process. Can the above code be modifed to write to a mp4 container directly? I see that you use avi container as well. How would one go about changing it to a mp4 container. I know that simply using “.mp4” extension does not solve the issue.
Thanks and regards.
Hi Michael,
haven’t tried it so far. But you should have a look at this thread: http://www.aforgenet.com/forum/viewtopic.php?f=2&t=2695
It seems that it’s possible to write directly into a mp4/h264 container, but therefore you have to tweak the AForge library a little bit.
Same as previous user, do you know how to make it work on .NET 4.0 or 4.5 platform? or do you know any other library that can do something similar?
Same question as I asked “the previous user”. Which libraries are missing and/or incompatible. Tell, so that I can search for a fix.
Hello,
Thanks for your replay. There is actually no missing libraries. I just get the following run time error:
“Could not load file or assembly ‘AForge.Video.FFMPEG, Version=2.2.5.0, Culture=neutral, PublicKeyToken=03563089b1be05dd’ or one of its dependencies. An attempt was made to load a program with an incorrect format.”
I did not set the project to 3.5 (I needed it for 4.0 at least). I even try to load the AForge.Video.FFMPEG downloaded from the following site:
https://aforgeffmpeg.codeplex.com/
but no success so far.
What I really one is just the nice same example you provide but for WPF app.
Was Camilo’s question ever resolved?
Thank you very much for this. Do you know if there are libraries to do the same on .NET 4.0 or 4.5 platform ?
Which libraries are missing?
Great sample code ever. Easily generate video from images (JPG files).
Now, how can I add a sound (or several sounds or songs) for the video ?
For example, I want include a Lady Gaga music at 00:34 minute in the video, another Maddona song at 02:47 minute, and another Julio Iglesias song at 04:56 minute?
It’s great mister.
I’m thinking…
How generating video from a sequence of images in C#?
How generating video from a sequence of images in C# and then added any sounds (from wav, mp3, mp4 file?)
“How generating video from a sequence of images in C#?”
The article above describes how to merge multiple images (i.e. frames) to a video file.
“[…] and then added any sounds (from wav, mp3, mp4 file?)”
Have a look at the following C# article on codeproject. It describes a wrapper for AVIlib and also shows how to add sound to video files using the library.
http://www.codeproject.com/Articles/7388/A-Simple-C-Wrapper-for-the-AviFile-Library
I need to capture the audio from the sound card using c# . Help me with this
writer.Open(“C:\\Test.wmv”,size.Width,size.Height);
In the Above line am getting exception as IO exception was unhandled cannot open the file. assist me to solve this issue.
I need help in capturing screen activities as images and save it in local disk. am able to save single images where as i need the help for capturing whole screen activities and save it as multiple images using C#
What about looping your code to get a continuous stream of screenshots. ;)
Yeah i got the continuous stream of screen shots. Where as now i need help in generating the video for that continuous stream of screen shots.
Hi Raffi,
Thanks dude. Its working fine. One more issue fr me i need to capture the video through webcam and save it to localdisk. Please assist me with this issue. Its urgent
This article shows you how to create a video from single images. Combine this article with the following: http://en.code-bude.net/2013/01/02/how-to-easily-record-from-a-webcam-in-c/
One shows you how to capture single frames from a webcam and the other shows you how to save single frames as a video.
If you need more help, write me again. ;)
I’m using the following code for recording the webcam video and saving it in local disk. Will this one work? Please help me out.
And also while debugging am getting the exception as IO exception”Failed opening the specified file.” Please help me out this to resolve these issues.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AForge.Video;
using AForge.Video.DirectShow;
using AForge.Video.FFMPEG;
using AForge.Video.VFW;
namespace aforgeCapture
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
VideoCaptureDevice videoSource;
private void Form1_Load(object sender, EventArgs e)
{
FilterInfoCollection videosources = new FilterInfoCollection(FilterCategory.VideoInputDevice);
if (videosources != null)
{
videoSource = new VideoCaptureDevice(videosources[0].MonikerString);
try
{
if (videoSource.VideoCapabilities.Length > 0)
{
string highestSolution = “0;0”;
for (int i = 0; i Convert.ToInt32(highestSolution.Split(‘;’)[0]))
highestSolution = videoSource.VideoCapabilities[i].FrameSize.Width.ToString() + “;” + i.ToString();
}
videoSource.DesiredFrameSize = videoSource.VideoCapabilities[Convert.ToInt32(highestSolution.Split(‘;’)[1])].FrameSize;
}
}
catch { }
videoSource.NewFrame += new AForge.Video.NewFrameEventHandler(videoSource_NewFrame);
videoSource.Start();
}
}
void videoSource_NewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs)
{
pictureBox1.BackgroundImage = (Bitmap)eventArgs.Frame.Clone();
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if (videoSource != null && videoSource.IsRunning)
{
videoSource.SignalToStop();
videoSource = null;
}
}
private void button1_Click(object sender, EventArgs e)
{
AVIWriter writer = new AVIWriter(“wmv3”);
writer.Open(“D\\:Gatiks.avi”, 320, 240);
Bitmap image = new Bitmap(320, 240);
for (int i = 0; i < 240; i++)
{
image.SetPixel(i, i, Color.Red);
writer.AddFrame(image);
}
writer.Close();
}
}
}
Hi Raffi,
The specified module could not be found. (Exception from HRESULT: 0x8007007E)
I’m getting the above error please assist me
This code is helpful! But I have a question. I have a program that streams video from a webcam and returns every image as bitmap. My question is how can I make those individual images be saved as a video clip? Thanks very much! I cannot connect it to your program. I am still finding a workaround. Thank you.
Are the single frames saved as bitmap files or why should it be impossible to use my code? Maybe you could use ffmpeg to make a video from the single frame files.
Perfect, just what I needed!
Yes I changed those settings as article says,but no good result.
When i try to run your example project it says “The selected file is a solution file,but was created by a newer version of this application and cannot be opened”.I am using Microsoft Visual Studio 2010.Is this the problem?
thanks
I really don’t know, why your project isn’t working, but I know why mine isn’t working for you. I’m using Visual Studio 2012 and Visual Studio solution files aren’t backward compatible. Just try to open the .csproj-file instead of the .sln file. This should work for you.
Hi..
I did the things as you mention above.But when i clicked the button i get following error
Could not load file or assembly ‘AForge.Video, Version=2.2.4.0, Culture=neutral, PublicKeyToken=cbfb6e07d173c401’ or one of its dependencies. The located assembly’s manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
pls help..
thanks
Did you manage both mentioned points/settings from the preparations section of the article? (Keywords: target plattform == x86, target framework version <= 3.5) Have you tried to download my example project (The one linked in the above article)? Did this run for you?
Hey! Thank you so much for this. Your code is so helpful!
I did however run into this same option…. ^^^
i am making my own bitmap files and then adding them into the stream through alpha blending, but I added a few more classes from my other project and then getting everything together, the same error comes up… I am also troubleshooting this issue. :C
If you know how to fix this, I would greatly appreciate it, I will post a solution if i figure it out!
Thanks!
-Cameron
Not altering the code from the downloaded file works great, its just when I add more code to it, this error seems to start really early in the code, I have it before any of my code starts to run and this is the first breaking point that stops the program from working. I am not sure why but the line
VideoFileWriter writer = new VideoFileWriter();
writer.Open(“FinalVideo.avi”, width, height, 24, VideoCodec.MPEG4, 1000000);
throws the file not found exception.
using what i downloaded I was able to delete the video created, run the program and have it work, and a new final video would be created, but this seems to break after adding things.
hope this helps?
SO, I had to re-add all the files in the debug folder from the original project you posted, and this worked! thanks, and sorry for the false alarm!!!
Great code! I will cite you in my project!
-Cameron
Thanks for your positive feedback!