I am just learning C# and I was trying to implement a webcam picture capture program. I'm using the Aforge library, the thing is that my picturebox is not displaying the webcam image and I don't understand why. If anyone knows my error, please let me know. Thank you in advance.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using DarrenLee.Media;
namespace test4
{
public partial class MainForm : Form
{
int count = 0;
Camera myCamera = new Camera();
public MainForm()
{
InitializeComponent();
GetInfo();
myCamera.OnFrameArrived += myCamera_OnFrameArrived;
}
private void GetInfo()
{
var cameraDevices = myCamera.GetCameraSources();
var cameraResolutions = myCamera.GetSupportedResolutions();
foreach (var d in cameraDevices)
cmbCameraDevices.Items.Add(d);
foreach (var r in cameraResolutions)
cmbCameraResolutions.Items.Add(r);
cmbCameraDevices.SelectedIndex = 0;
cmbCameraDevices.SelectedIndex = 0;
}
private void myCamera_OnFrameArrived(object source, FrameArrivedEventArgs e)
{
Image img = e.GetFrame();
picCamera.Image = img;
}
void ComboBox1SelectedIndexChanged(object sender, EventArgs e)
{
myCamera.ChangeCamera(cmbCameraDevices.SelectedIndex);
}
void ComboBox2SelectedIndexChanged(object sender, EventArgs e)
{
myCamera.Start(cmbCameraDevices.SelectedIndex);
}
void Form1FormClosing(object sender, FormClosingEventArgs e)
{
myCamera.Stop();
}
void BTTsaveClick(object sender, EventArgs e)
{
string filename = Application.StartupPath + #"\" + "Image" + count.ToString();
myCamera.Capture(filename);
count++;
}
}
}
Picture of how it looks when I compile it:
https://i.gyazo.com/6956a07405cd4bf5e74c20bc321bd32e.png
I am connecting the picture box with the content in this line:
Image img = e.GetFrame();
picCamera.Image = img;
Make sure you click on the object before writing the code.
Example: Click on the button in the design form then paste the code for BTTsaveClick in the newly created method after clicking on the button.
If you are using Visual Studio, you can check if the methods are referenced. If it's not referenced, that means the code won't be read.
Related
Was following a tutorial on YouTube and tried to get my program to display the live video feed from my webcam into the forms picture box but for some reason the webcam comes on but the picture box isn't displaying anything
I have tried checking if the Mat class was returning null.
but it isn't this is my code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Emgu.CV;
using Emgu.CV.Structure;
using Emgu.CV.UI;
namespace FaceRecognitionAttandanceSystem
{
public partial class StudentAdd : Form
{
public string fileName { get; set; }
VideoCapture capture;
public StudentAdd()
{
InitializeComponent();
}
//Open Folder
private void metroButton3_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog() { Filter = "JPEG|*.jpg", ValidateNames = true, Multiselect = false };
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
//open file explorer
fileName = openFileDialog.FileName;
//pick image from file
Image img = Image.FromFile(fileName);
//Rotates Image by 90degrees
img.RotateFlip(RotateFlipType.Rotate90FlipNone);
pictureBox2.Image = img;
}
}
}
//Capture Image
private void metroButton4_Click(object sender, EventArgs e)
{
//If capture is empty start new video capture
if(capture == null)
{
capture = new Emgu.CV.VideoCapture(0);
}
capture.ImageGrabbed += Capture_ImageGrabbed;
capture.Start();
}
private void Capture_ImageGrabbed(object sender, EventArgs e)
{
try
{
Mat mat = new Mat();
if(mat == null)
{
Console.WriteLine("Here you Go");
}
capture.Retrieve(mat);
pictureBox1.Image = mat.ToImage<Bgr, Byte>().ToBitmap<Bgr, Byte>();
}
catch(Exception)
{
}
}
private void metroButton5_Click(object sender, EventArgs e)
{
}
}
}
The problem is very likely that the Capture_ImageGrabbed event is raised on a background thread. And you can only update the UI on the UI thread. You can place a break point in the event-handler and check the thread-debug window to confirm. To fix this you need to move execution to the UI thread. Try:
capture.Retrieve(mat);
var bitmap = mat.ToImage<Bgr, Byte>().ToBitmap<Bgr, Byte>();
pictureBox1.Invoke(() => pictureBox1.Image = bitmap );
You might need to write Invoke((Action)(() => pictureBox1.Image = bitmap) ), since I think there is some issues with the overload resolution of lambdas with the invoke-method.
I am making a desktop app in c# in which when the user selects specific name of background from the menu strip, then the background shall turn to that required background. The problem is that i cannot save the user input, i tried settings but i cannot find "system.drawing.image" in settings so is there any way i can save the user changed background ? No external backgrounds a user is allowed to change, just the ones in the resource folder. Here is my code which shows error that system.drawing.color cannot take place of drawing.image.
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 TAC
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
panel1.Location = new Point(165, 157);
panel2.Location = new Point(289, 158);
panel3.Location = new Point(47, 275);
panel4.Location = new Point(47, 402);
this.BackgroundImage = Properties.Settings.Default.FormImage;
}
private void bLUEToolStripMenuItem_Click(object sender, EventArgs e)
{
this.BackgroundImage = TAC.Properties.Resources.tex1;
}
private void gREENToolStripMenuItem_Click(object sender, EventArgs e)
{
this.BackgroundImage = TAC.Properties.Resources.tex2;
}
private void oRANGEToolStripMenuItem_Click(object sender, EventArgs e)
{
this.BackgroundImage = TAC.Properties.Resources.tex3;
}
private void rEDToolStripMenuItem_Click(object sender, EventArgs e)
{
this.BackgroundImage = TAC.Properties.Resources.tex4;
}
private void pURPLEToolStripMenuItem_Click(object sender, EventArgs e)
{
this.BackgroundImage = TAC.Properties.Resources.tex5;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Properties.Settings.Default.FormImage = this.BackgroundImage;
}
}
}
Use Save method to save settings
Properties.Settings.Default.Save();
If you want add an image to settings :
Add new setting with type string and use like this:
Save an image to setting ( when you close form)
MemoryStream ms = new MemoryStream();
Propertis.Resources.MyImage.Save(ms,ImageFormat.Jpeg);
Properties.Settings.Default.BackImg = Convert.ToBase64String(ms.ToArray());
Properties.Settings.Default.Save();
And read image from setting and set to background(in form load)
string img = Properties.Settings.Default.BackImg ;
byte[] i = Convert.FromBase64String(img);
this.BackgroundImage = Image.FromStream(new MemoryStream(i));
How add custom settings ?
http://www.codeproject.com/Articles/29130/Windows-Forms-Creating-and-Persisting-Custom-User
I'm currently having issues with my code in terms of getting a printing option to show up when thy click a specific button.
I am making a reminder program and was just experimenting. Also would like to know the most efficient way to add a daily notification system to my program
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Mail;
using System.IO;
using System.Drawing.Printing;
using System.Security;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
namespace simpleapp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Add("Reminder: " + textBox1.Text);
}
private void input_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Enter)
{
listBox1.Items.Add("Reminder: " + textBox1.Text );
}
}
private void button2_Click(object sender, EventArgs e)
{
for (int rmd = listBox1.SelectedIndices.Count - 1; rmd >= 0; rmd--)
{
listBox1.Items.RemoveAt(listBox1.SelectedIndices[rmd]);
}
}
private void Form1_Load(object sender, EventArgs e)
{
listBox1.SelectionMode = SelectionMode.MultiExtended;
}
private void button6_Click(object sender, EventArgs e)
{
FAQ faqs = new FAQ();
faqs.Show();
}
// When the Button is Clicked the List is saved in a ".txt file format for the user to view later
private void button3_Click(object sender, EventArgs e)
{
var Savingfileas = new SaveFileDialog();
Savingfileas.Filter = "Text (*.txt)|*.txt ";
if (Savingfileas.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
using (var Reminder = new StreamWriter(Savingfileas.FileName, false))
foreach (var item in listBox1.Items)
Reminder.Write(item.ToString() + Environment.NewLine);
MessageBox.Show("File has been successfully saved"+ '\n' + "Thank you for using the Remindr program");
}
}
private void button4_Click(object sender, EventArgs e)
{
}
private void button5_Click(object sender, EventArgs e)
{
Email_Client emc = new Email_Client();
emc.Show();
}
}
}
You have a few options. One is to graphically layout a print document and iterate through your listbox while drawing the text in the textbox using x and y coordinates. A better way would be to get your listbox items into a dataset and use it to generate a report. Are you storing these items in a database for retrieval? Here's a link that should help you get started. The tutorial is in VB.Net but there's only a small amount of code to this and should be easy to repeat using C# code.
Here is an absolutely minimal example of printing a ListBox.
It assumes your ListBox contains strings and shows a PrintPreviewDialog; it sets the page unit to mm, do pick a unit you are comfortable with..!
Of course you may chose one or more different fonts etc..
private PrintDocument document = new PrintDocument();
private void printButton_Click(object sender, EventArgs e)
{
PrintPreviewDialog ppd = new PrintPreviewDialog();
ppd.Document = document;
ppd.Document.DocumentName = "TESTING";
document.PrintPage += document_PrintPage;
ppd.ShowDialog();
}
void document_PrintPage(object sender, PrintPageEventArgs e)
{
e.Graphics.PageUnit = GraphicsUnit.Millimeter;
int leading = 5;
int leftMargin = 25;
int topMargin = 10;
// a few simple formatting options..
StringFormat FmtRight = new StringFormat() { Alignment = StringAlignment.Far};
StringFormat FmtLeft = new StringFormat() { Alignment = StringAlignment.Near};
StringFormat FmtCenter = new StringFormat() { Alignment = StringAlignment.Near};
StringFormat fmt = FmtRight;
using (Font font = new Font( "Arial Narrow", 12f))
{
SizeF sz = e.Graphics.MeasureString("_|", Font);
float h = sz.Height + leading;
for (int i = 0; i < listBox1.Items.Count; i++)
e.Graphics.DrawString(listBox1.Items[i].ToString(), font , Brushes.Black,
leftMargin, topMargin + h * i, fmt);
}
}
The actual printing is triggered when the user clicks the printer symbol in the dialog.
Note that there are more StringFormat options!
I wrote a code for acessing the webcam with two buttons and a picture box
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.Imaging;
using AForge.Imaging.Filters;
using AForge.Video;
using AForge.Video.DirectShow;
namespace cam
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private FilterInfoCollection webcam;
private VideoCaptureDevice cam;
Bitmap bitmap;
private void Form1_Load(object sender, EventArgs e)
{
webcam = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach (FilterInfo VideoCaptureDevice in webcam)
{
comboBox1.Items.Add(VideoCaptureDevice.Name);
}
comboBox1.SelectedIndex = 0;
}
private void button1_Click(object sender, EventArgs e)
{
cam = new VideoCaptureDevice(webcam[comboBox1.SelectedIndex].MonikerString);
cam.NewFrame += new NewFrameEventHandler(cam_NewFrame);
cam.Start();
}
void cam_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
Bitmap bitmap = (Bitmap)eventArgs.Frame.Clone();
pictureBox1.Image = bitmap;
}
private void button3_Click(object sender, EventArgs e)
{
if (cam.IsRunning)
{
cam.Stop();
}
}
private void pictureBox1_Click(object sender, EventArgs e)
{
pictureBox1.Image = bitmap;
}
}
}
The code build up successfully. but on debugging the picture box is not working. start and stop is working properly. Can anyone help?
you have to delete first
Bitmap bitmap;
because its null and that what you show in picture box
not the picture that come from camera
a long time ago i had problems too with aforge but got it working
see my code inhere : How initialize AForge webcam
Trying to put icons in ObjectListview, here's my piece of code where icon should have been put:
objectListView1.SmallImageList = imageList1;
deleteColumn.IsEditable = true;
deleteColumn.ImageGetter = delegate
{
return 0;
};
deleteColumn.AspectGetter = delegate
{
return "Delete";
};
imageList1 already have an image, this code should have put an icon next to "Delete", but it did not appear at all, looked through cookbooks and Google and I still have no idea. Can anyone help me?
this is the full form code in case needed:
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 System.Security.Cryptography;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
objectListView1.AllowDrop = true;
objectListView1.DragEnter += new DragEventHandler(objectListView1_DragEnter);
objectListView1.DragDrop += new DragEventHandler(objectListView1_DragDrop);
objectListView1.CellEditActivation = BrightIdeasSoftware.ObjectListView.CellEditActivateMode.SingleClick;
objectListView1.CellEditStarting += deleteItems;
objectListView1.SmallImageList = imageList1;
deleteColumn.IsEditable = true;
deleteColumn.ImageGetter = delegate
{
return 0;
};
deleteColumn.AspectGetter = delegate
{
return "Delete";
};
}
private void objectListView1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void objectListView1_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop, true))
{
string[] droppedFiles = (string[]) e.Data.GetData(DataFormats.FileDrop);
foreach (string path in droppedFiles)
{
if (File.Exists(path))
{
FileObject fo = new FileObject(path, "added later");
objectListView1.AddObject(fo);
}
}
}
}
private void deleteItems(object sender, BrightIdeasSoftware.CellEditEventArgs e)
{
if(e.Column == deleteColumn)
{
e.Cancel = true;
objectListView1.RemoveObject(e.RowObject);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
In order for images to appear next to the text in a column, you must:
Connect the ObjectListView to an ImageList (using the SmallImageList property);
Install an ImageGetter delegate for the column that must show the images;
Make sure that there are actually images in the ImageList.
With this done, images will appear (I just tested this).
There is one catch, though. From your question, I suspect that the "Delete" column may not be the first column in the ObjectListView. The above steps only allow you to show an image in the very first column. For subsequent columns, you will have to set the ShowImagesOnSubItems property to True. Could that be it?