I've got application page where is view from street camera. Photo form camera is refreshing about every 30 sec.
I created a button which is used to refresh photo.
I want to add progress indicator which will be show every time when photo is downloading.
I don't know how and where exactly I have to add code.
I tried many examples but fail.
Because I don't really understand how to turn it on and off.
public void downloading()
{
WebClient webClient = new WebClient();
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(ImageOpenReadCompleted);
webClient.OpenReadAsync(new Uri("http://przeprawa.swi.pl/cgi-bin/kam.cgi?6&1399042906515&" + Guid.NewGuid()));
}
private void ImageOpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (!e.Cancelled && e.Error == null)
{
BitmapImage bmp = new BitmapImage();
bmp.SetSource(e.Result);
image1.Source = bmp;
}
}
public void Refresh(object sender, EventArgs e)
{
downloading();
}
Make this change to your code:
public void downloading()
{
WebClient webClient = new WebClient();
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(ImageOpenReadCompleted);
webClient.OpenReadAsync(new Uri("http://przeprawa.swi.pl/cgi-bin/kam.cgi?6&1399042906515&" + Guid.NewGuid()));
var _progressIndicator = new ProgressIndicator
{
IsIndeterminate = true,
IsVisible = true,
Text = "Downloading...",
};
SystemTray.SetProgressIndicator(this, _progressIndicator);
}
private void ImageOpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (!e.Cancelled && e.Error == null)
{
BitmapImage bmp = new BitmapImage();
bmp.SetSource(e.Result);
image1.Source = bmp;
var _progressIndicator = new ProgressIndicator
{
IsVisible = false,
};
SystemTray.SetProgressIndicator(this, _progressIndicator);
}
}
public void Refresh(object sender, EventArgs e)
{
downloading();
}
Related
I have a problem about System.Windows.Forms.PictureBox. I want to show a image on monitor and capture it on the camera. So I use Winform which include a picturebox. The picture box is:
PictureBox pb = new PictureBox();
pb.WaitOnLoad = true;
When I set a bitmap to PictureBox and capture the image from camera,
// Show bmp1
this.image.Image = bmp1;
this.image.Invalidate();
this.image.Refresh();
// Delay 1s
UseTimerToDelay1s();
// Show bmp2
this.image.Image = bmp2;
this.image.Invalidate();
this.image.Refresh();
// Capture
CaptureImageFromCamera();
It only capture the bmp1.
If I add a small delay like this,
this.image.Image = bmp2;
this.image.Invalidate();
this.image.Refresh();
UseTimerToDelay100ms();
CaptureImageFromCamera();
It capture bmp2. The Image set method seem to be a async method. Does any method to confirm the image is set? Thanks.
I'd use the first Paint event after assigning the new Image.
You can give it a try using a very large image url from this site.
The example uses google logo image url. Copy the following code and make sure you assign event handlers to the events:
bool newImageInstalled = true;
private void Form1_Load(object sender, EventArgs e)
{
pictureBox1.WaitOnLoad = true;
}
private void PictureBox1_Paint(object sender, PaintEventArgs e)
{
if (!newImageInstalled)
{
newImageInstalled = true;
BeginInvoke(new Action(() =>
{
//Capturing the new image
using (var bm = new Bitmap(pictureBox1.ClientSize.Width,
pictureBox1.ClientSize.Height))
{
pictureBox1.DrawToBitmap(bm, pictureBox1.ClientRectangle);
var tempFile = System.IO.Path.GetTempFileName() + ".png";
bm.Save(tempFile, System.Drawing.Imaging.ImageFormat.Png);
System.Diagnostics.Process.Start(tempFile);
}
}));
}
}
private void button1_Click(object sender, EventArgs e)
{
newImageInstalled = false;
pictureBox1.ImageLocation =
"https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
}
private void button2_Click(object sender, EventArgs e)
{
newImageInstalled = false;
pictureBox1.Image = null;
}
In my form. I have two picturebox and a button that capture the image into picturebox.
Two Picturebox
WebcamImage - represent the live camera image
PreviewImage - represent the Captured image from webcamimage
When i saved this captured image it will go to my UserImage picturebox (In my Usercontrol)
The problems is i don't know how i'm gonna get the picturebox image path.
What i want is when i click my saved button the image path will be saved to my label text.
Here's my code
PS: I'm using Aforge.dll
public partial class CaptureImage : Form
{
private FilterInfoCollection CaptureDevice;
private VideoCaptureDevice FinalFrame;
RegisterCustomer _view;
public CaptureImage(RegisterCustomer view)
{
InitializeComponent();
this._view = view;
}
private void CaptureImage_Load(object sender, EventArgs e)
{
CaptureDevice = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach (FilterInfo Device in CaptureDevice)
{
comboBox1.Items.Add(Device.Name);
}
comboBox1.SelectedIndex = 0;
FinalFrame = new VideoCaptureDevice();
FinalFrame = new VideoCaptureDevice(CaptureDevice[comboBox1.SelectedIndex].MonikerString);
if (FinalFrame.VideoCapabilities.Length > 0)
{
string highestSolution = "0;0";
//Search for the highest resolution
for (int i = 0; i < FinalFrame.VideoCapabilities.Length; i++)
{
if (FinalFrame.VideoCapabilities[i].FrameSize.Width > Convert.ToInt32(highestSolution.Split(';')[0]))
highestSolution = FinalFrame.VideoCapabilities[i].FrameSize.Width.ToString() + ";" + i.ToString();
}
}
FinalFrame.NewFrame += new NewFrameEventHandler(FinalFrame_NewFrame);
FinalFrame.Start();
btn_save.Hide();
btn_cancel.Hide();
}
void FinalFrame_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
WebcamImage.Image = (Bitmap)eventArgs.Frame.Clone();
}
private void CaptureImage_FormClosing(object sender, FormClosingEventArgs e)
{
if (FinalFrame.IsRunning == true)
{
FinalFrame.Stop();
}
}
private void btn_save_Click(object sender, EventArgs e)
{
_view.UserImage.Image = PreviewImage.Image;
this.Close();
}
private void btn_cancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void btn_capture_Click(object sender, EventArgs e)
{
PreviewImage.Image = (Bitmap)WebcamImage.Image.Clone();
PreviewImage.BringToFront();
btn_capture.Hide();
btn_save.Show();
btn_cancel.Show();
}
}
This is only i know in getting the picturebox image path by using openfile dialog
using (OpenFileDialog ofd = new OpenFileDialog())
{
ofd.Filter = "Image Files (*.jpg;*.jpeg;.*.png; | *.jpg;*.jpeg;.*.png;)";
ofd.FilterIndex = 1;
ofd.Multiselect = false;
ofd.Title = "Select Image File";
if (ofd.ShowDialog() == DialogResult.OK)
{
location = ofd.FileName;
path.Text = location;
UserImage.Image = Image.FromFile(location);
UserImage.SizeMode = PictureBoxSizeMode.StretchImage;
}
}
I am currently making a podcast client to download episodes. I have got a listView filled with the episodes for a feed and then when you double click on one it places it into a separate 'downloads' lisview which has a 'name' and a 'progress' column.
The problem I am having is trying to individually update each progress while downloading asynchronously. As I am not sure of how to keep track of the progress for each ListViewItem and how to reference it in the downloadProgressChanged function.
private void lvPodDownloads_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (lvPodEpisodes.SelectedItems.Count == 1) // Check if an item is selected just to be safe
{
ListViewItem item = (ListViewItem)lvPodEpisodes.SelectedItem;
string[] epInfo = (string[])item.Tag;
txtTitle.Text = epInfo[0];
txtDesc.Text = epInfo[1];
try
{
imgFeedImage.Source = new BitmapImage(new Uri((Environment.CurrentDirectory + "\\..\\..\\feedImages\\" + epInfo[3])));
}
catch (Exception) // If it fails to set the image (Eg. It's non-existent) It will leave it blank
{
imgFeedImage.Source = null;
}
}
}
private void lvPodEpisodes_MouseDoubleClick(object sender, MouseButtonEventArgs e) // Downloading the episode in here
{
if (e.ChangedButton == MouseButton.Left) // Left button was double clicked
{
ListViewItem selected = (ListViewItem)lvPodEpisodes.SelectedItem;
string[] epInfo = (string[])selected.Tag;
Uri downloadUrl = new Uri(epInfo[2]);
List<Episode> downloading = new List<Episode>();
downloading.Add(new Episode() { Title = epInfo[0], Progress = "0%" });
lvPodDownloads.Items.Add((new Episode() { Title = epInfo[0], Progress = "0%" }));
using (WebClient client = new WebClient())
{
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
}
}
}
static int intDownloadProgress = new int();
private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
intDownloadProgress = e.ProgressPercentage;
}
private void Completed(object sender, AsyncCompletedEventArgs e)
{
MessageBox.Show("Download completed!");
}
This is a code sample of the downloading section of the program.
Here is an image of what I have so far:
https://s33.postimg.cc/gthzioxlr/image.png
You should add an extra argument to your ProgressChanged method.
private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e, Episode curEpisode)
{
curEpisode.Progress = $"{e.ProgressPercentage} %";
}
And to modify the handler setting like that:
List<Episode> downloading = new List<Episode>();
var newEpisode = new Episode() { Title = epInfo[0], Progress = "0%" };
downloading.Add(newEpisode);
lvPodDownloads.Items.Add(newEpisode);
using (WebClient client = new WebClient())
{
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler((sender, e) => ProgressChanged(sender, e, newEpisode));
}
The static property intDownloadProgress is then useless.
You should also think about using an observable collection for the episode list and using it for the binding via the XAML code.
I am trying to develop a WindowsForm Application which will use webcamera to detect QRCode and decode the message. For this I am using AForge.NET and ZXing.NET.
So far, I have been able to figure out how to decode the QRCode from an URI, but I want to detect the QRCode from webcamera, and decode it.
Below is the sample to my code.
public String Decode(Uri uri)
{
Bitmap image;
try
{
image = (Bitmap)Bitmap.FromFile(uri.LocalPath);
}
catch (Exception ex)
{
throw new FileNotFoundException("Resource not found: " + uri);
}
using (image)
{
String text = "";
LuminanceSource source = new BitmapLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result = new MultiFormatReader().decode(bitmap);
if (result != null)
{
text = result.Text;
return text;
}
text = "Provided QR couldn't be read.";
return text;
}
}
private FilterInfoCollection videoDevices;
private VideoCaptureDevice videoSource;
private Bitmap capturedImage;
private String message = "";
public FormQRCodeScanner()
{
InitializeComponent();
}
private void FormQRCodeScanner_Load(object sender, EventArgs e)
{
videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach (FilterInfo device in videoDevices)
{
comboBoxCameraSource.Items.Add(device.Name);
}
comboBoxCameraSource.SelectedIndex = 0;
videoSource = new VideoCaptureDevice();
buttonStartStop.Text = "Start";
buttonCapture.Enabled = false;
buttonDecode.Enabled = false;
}
private void FormQRCodeScanner_FormClosing(object sender, FormClosingEventArgs e)
{
if (videoSource.IsRunning)
{
videoSource.Stop();
}
}
void videoSource_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
Bitmap image = (Bitmap) eventArgs.Frame.Clone();
pictureBoxSource.Image = image;
}
private void buttonStartStop_Click(object sender, EventArgs e)
{
if (videoSource.IsRunning)
{
videoSource.Stop();
pictureBoxSource.Image = null;
pictureBoxCaptured.Image = null;
pictureBoxSource.Invalidate();
pictureBoxCaptured.Invalidate();
buttonStartStop.Text = "Start";
buttonCapture.Enabled = false;
buttonDecode.Enabled = false;
}
else
{
videoSource = new VideoCaptureDevice(videoDevices[comboBoxCameraSource.SelectedIndex].MonikerString);
videoSource.NewFrame += new NewFrameEventHandler(videoSource_NewFrame);
videoSource.Start();
buttonStartStop.Text = "Stop";
buttonCapture.Enabled = true;
buttonDecode.Enabled = true;
}
}
private void buttonCapture_Click(object sender, EventArgs e)
{
if (videoSource.IsRunning)
{
pictureBoxCaptured.Image = (Bitmap)pictureBoxSource.Image.Clone();
capturedImage = (Bitmap)pictureBoxCaptured.Image;
}
}
private void buttonDecode_Click(object sender, EventArgs e)
{
if (capturedImage != null)
{
ExtractQRCodeMessageFromImage(capturedImage);
richTextBoxMessage.Text = message;
richTextBoxMessage.ReadOnly = true;
}
}
private string ExtractQRCodeMessageFromImage(Bitmap bitmap)
{
try
{
BarcodeReader reader = new BarcodeReader
(null, newbitmap => new BitmapLuminanceSource(bitmap), luminance => new GlobalHistogramBinarizer(luminance));
reader.AutoRotate = true;
reader.TryInverted = true;
reader.Options = new DecodingOptions { TryHarder = true };
var result = reader.Decode(bitmap);
if (result != null)
{
message = result.Text;
return message;
}
else
{
message = "QRCode couldn't be decoded.";
return message;
}
}
catch (Exception ex)
{
message = "QRCode couldn't be detected.";
return message;
}
}
**For this you should install these packages
Install-Package AForge
Install-Package AForge.Video
Install-Package AForge.Video.DirectShow
Install-Package ZXing.Net
you can watch this video for more help
https://www.youtube.com/watch?v=wcoy0Gwxr50**
using System.IO;
using AForge;
using AForge.Video;
using AForge.Video.DirectShow;
using ZXing;
using ZXing.Aztec;
private void Form1_Load(object sender, EventArgs e)
{
CaptureDevice = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach (FilterInfo Device in CaptureDevice)
{
comboBox1.Items.Add(Device.Name);
}
comboBox1.SelectedIndex = 0;
FinalFrame = new VideoCaptureDevice();
}
private void button1_Click(object sender, EventArgs e)
{
FinalFrame = new VideoCaptureDevice(CaptureDevice[comboBox1.SelectedIndex].MonikerString);
FinalFrame.NewFrame += new NewFrameEventHandler(FinalFrame_NewFrame);
FinalFrame.Start();
}
private void FinalFrame_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
pictureBox1.Image = (Bitmap)eventArgs.Frame.Clone();
}
private void timer1_Tick(object sender, EventArgs e)
{
BarcodeReader Reader = new BarcodeReader();
Result result = Reader.Decode((Bitmap)pictureBox1.Image);
try
{
string decoded = result.ToString().Trim();
if (decoded != "")
{
timer1.Stop();
MessageBox.Show(decoded);
Form2 form = new Form2();
form.Show();
this.Hide();
}
}
catch(Exception ex){
}
}
private void button2_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
timer1.Start();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (FinalFrame.IsRunning == true)
{
FinalFrame.Stop();
}
}
I'm using the AForge.NET library (http://www.aforgenet.com) to capture an image from my webcam,show it in a picturebox and then save it.But the capture is not like mirror. Does anybody know how to mirror the capture in c#?
public static Bitmap _latestFrame;
private FilterInfoCollection webcam;
private VideoCaptureDevice cam;
Bitmap bitmap;
private int orderidcapture = 0;
private string date1 = "";
private void Frm_Capturet_Load(object sender, EventArgs e)
{
try
{
piclocation = new Ini(Application.StartupPath + "\\UserSetting.ini").GetValue("Webservice",
"DigitalSign").ToString();
webcam = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach (FilterInfo VideoCaptureDevice in webcam)
{
comboBox1.Items.Add(VideoCaptureDevice.Name);
}
comboBox1.SelectedIndex = 0;
}
catch (Exception error)
{
MessageBox.Show(error.Message + "error11");
}
Focus();
}
private string piclocation = "";
void cam_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
bitmap = (Bitmap)eventArgs.Frame.Clone();
picFrame.Image = bitmap;
}
private void button1_Click(object sender, EventArgs e)
{
cam = new VideoCaptureDevice(webcam[comboBox1.SelectedIndex].MonikerString);
cam.NewFrame += new NewFrameEventHandler(cam_NewFrame);
cam.DisplayPropertyPage(new IntPtr(0));
cam.Start();
}
private void button2_Click(object sender, EventArgs e)
{
date1 = date1.Replace("/", "");
Bitmap current = (Bitmap)bitmap.Clone();
string filepath = Environment.CurrentDirectory;
string fileName = System.IO.Path.Combine(piclocation, orderidcapture + "__" + date1 + #"name.jpg");
current.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
current.Dispose();
current = null;
}
solved the problem by my own.
void cam_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
try
{
bitmap = (Bitmap)eventArgs.Frame.Clone();
///add these two lines to mirror the image
var filter = new Mirror(false, true);
filter.ApplyInPlace(bitmap);
///
picFrame.Image = bitmap;
}
catch
{
}
}