PhotoChooserTask how to pass extra parameter Windows Phone - c#

Say I have this code
private void photoChooserBtn_Click(object sender, RoutedEventArgs e)
{
photoChooserTask = new PhotoChooserTask();
photoChooserTask.Completed += new EventHandler<PhotoResult (photoChooserTask_Completed);
photoChooserTask.Show();
}
private void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
BitmapImage bmp = new BitmapImage();
bmp.SetSource(e.ChosenPhoto);
imagecontrol.Source = bmp;
}
}
I have to repeat this code several times as I have several buttons. I want to avoid this.
I want to have one button click event. Then append extra parameter to photoChooserTask so that I can process the result in photoChooserTask_Completed event based on the parameter.
So in photoChooserBtn_Click event. I would like to do something like this.
Button btn = (Button)sender;
photoChooserTask.Tag = btn.Name;
Then
private void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
BitmapImage bmp = new BitmapImage();
bmp.SetSource(e.ChosenPhoto);
imagecontrol.Source = bmp;
string param = ((PhotoChooserTask)sender).Tag;
Switch (param)
{
case "bla":
case "bla2":
...........
}
}
What's the best way to do this?

What you are looking for is not possible. However you can add a string tag property to your page. Since only one PhotoChooserTask can run at a time, this approach should be fine.
public partial class MainPage : PhoneApplicationPage
{
string tag;
// Constructor
public MainPage()
{
InitializeComponent();
}
private void photoChooserBtn_Click(object sender, RoutedEventArgs e)
{
photoChooserTask = new PhotoChooserTask();
tag = (sender as Button).Name;
photoChooserTask.Completed += new EventHandler<PhotoResult>(photoChooserTask_Completed);
photoChooserTask.Show();
}
private void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
BitmapImage bmp = new BitmapImage();
bmp.SetSource(e.ChosenPhoto);
imagecontrol.Source = bmp;
switch(tag)
{
case tag1:
case tag2:
........
}
tag = null;
}
}

Related

Why it doesn't pick up any cameras?

I'm in making barcode scanner but "VideoCaptureDevice can't pick up any objects" ?
I'm using AForge video and ZXing in visual studio 2019 C#
I want it to be able to scan barcodes from my laptop webcam.
I tried running it with the problem but in my combobox where are supposed to be cameras available for use but they are none. I even tried activating the webcam before opening up the program.
code:
FilterInfoCollection FilterInfoCollection;
VideoCaptureDevice VideoCaptureDevice;
private void Form1_Load(object sender, EventArgs e)
{
FilterInfoCollection = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach (FilterInfo device in FilterInfoCollection)
comboBox1.Items.Add(device.Name);
comboBox1.SelectedIndex = 0;
}
private void button1_Click(object sender, EventArgs e)
{
VideoCaptureDevice = new VideoCaptureDevice(FilterInfoCollection[comboBox1.SelectedIndex].MonikerString);
VideoCaptureDevice.NewFrame += VideoCaptureDevice_NewFrame;
VideoCaptureDevice.Start();
}
private void VideoCaptureDevice_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
Bitmap bitmap = (Bitmap)eventArgs.Frame.Clone();
BarcodeReader reader = new BarcodeReader();
var result = reader.Decode(bitmap);
if (result != null)
{
textBox1.Invoke(new MethodInvoker(delegate ()
{
textBox1.Text = result.ToString();
}));
}
pictureBox1.Image = bitmap;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (VideoCaptureDevice != null)
{
if (VideoCaptureDevice.IsRunning)
VideoCaptureDevice.Stop();
}
}
}
}

How to Insert bitmap image to sqlite database on Windows phone 8.1 c#

I have managed to pick an image from the phones library and display it. this is the code. Question is how do i Insert this image into my Sqlite database of contacts and retrieve it and display it again after getting the image? Here is my code. A detailed step by step instruction would be appreciated from here.
namespace Mobile_Life.Pages
{
public sealed partial class NextOFKin_Update_Delete : Page
{
int Selected_ContactId = 0;
DatabaseHelperClass Db_Helper = new DatabaseHelperClass();
Contacts currentcontact = new Contacts();
CoreApplicationView view;
public NextOFKin_Update_Delete()
{
this.InitializeComponent();
HardwareButtons.BackPressed += HardwareButtons_BackPressed;
view = CoreApplication.GetCurrentView();
}
private void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
{
if (Frame.CanGoBack)
{
e.Handled = true;
Frame.GoBack();
}
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
await StatusBar.GetForCurrentView().ShowAsync();
Selected_ContactId = int.Parse(e.Parameter.ToString());
currentcontact = Db_Helper.ReadContact(Selected_ContactId);//Read selected DB contact
namestxt.Text = currentcontact.Name;//get contact Name
relationtxt.Text = currentcontact.Relation;//get contact relation
phonetxt.Text = currentcontact.PhoneNumber;//get contact PhoneNumber
}
private void Update_click(object sender, RoutedEventArgs e)
{
currentcontact.Name = namestxt.Text;
currentcontact.Relation = relationtxt.Text;
currentcontact.PhoneNumber = phonetxt.Text;
Db_Helper.UpdateContact(currentcontact);//Update selected DB contact Id
Frame.Navigate(typeof(NextOfKin));
}
private void Delete_click(object sender, RoutedEventArgs e)
{
Db_Helper.DeleteContact(Selected_ContactId);//Delete selected DB contact Id.
Frame.Navigate(typeof(NextOfKin));
}
private void profile_img(object sender, TappedRoutedEventArgs e)
{
FileOpenPicker filePicker = new FileOpenPicker();
filePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
filePicker.ViewMode = PickerViewMode.Thumbnail;
// Filter to include a sample subset of file types
filePicker.FileTypeFilter.Clear();
filePicker.FileTypeFilter.Add(".bmp");
filePicker.FileTypeFilter.Add(".png");
filePicker.FileTypeFilter.Add(".jpeg");
filePicker.FileTypeFilter.Add(".jpg");
filePicker.PickSingleFileAndContinue();
view.Activated += viewActivated;
}
private async void viewActivated(CoreApplicationView sender, IActivatedEventArgs args1)
{
FileOpenPickerContinuationEventArgs args = args1 as FileOpenPickerContinuationEventArgs;
if (args != null)
{
if (args.Files.Count == 0) return;
view.Activated -= viewActivated;
StorageFile storageFile = args.Files[0];
var stream = await storageFile.OpenAsync(FileAccessMode.Read);
var bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(stream);
var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream);
profile.ImageSource = bitmapImage;
}
}
}
The best way would be NOT to store the image in SQLite. Just copy it to your ApplicationData.Current.LocalFolder and save the path.
If you really want to store the BitmapImage in SQLite, just convert it to byte array: Convert a bitmapimage to byte[] array for storage in sqlite database

How to save only the image that is showing from my picturebox

I am trying to figure out how to save a snapshot of a video being shown from a picturebox control. I can already save an image file, however my problem is the whole image that is 'seen' by my camera is the one that is being saved. What I would like to save is the image that is only being shown from my picturebox control, which is just a portion of what the camera is capturing. By the way I am using Aforge framework set of video libraries.
My picturebox is set at Height = 400 and Width = 400.
Here is a sample of my code
private void Form1_Load(object sender, EventArgs e)
{
videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach (FilterInfo device in videoDevices)
{
drvrlist.Items.Add(device.Name);
}
drvrlist.SelectedIndex = 1;
videosource = new VideoCaptureDevice();
if (videosource.IsRunning)
{
videosource.Stop();
}
else
{
videosource = new VideoCaptureDevice(videoDevices[comboBox1.SelectedIndex].MonikerString);
videosource.NewFrame += new NewFrameEventHandler(videosource_NewFrame);
videosource.Start();
}
}
private void startbtn_Click(object sender, EventArgs e)
{
if (videosource.IsRunning)
{
videosource.Stop();
}
else
{
videosource = new VideoCaptureDevice(videoDevices[drvrlist.SelectedIndex].MonikerString);
videosource.NewFrame += new NewFrameEventHandler(videosource_NewFrame);
videosource.Start();
}
}
private void videosource_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
pictureBox1.Image = (Bitmap)eventArgs.Frame.Clone();
//throw new NotImplementedException();
}
private void save_btn_Click(object sender, EventArgs e)
{
SaveFileDialog savefilediag = new SaveFileDialog();
savefilediag.Filter = "Portable Network Graphics|.png";
if(savefilediag.ShowDialog()== System.Windows.Forms.DialogResult.OK)
{
if (pictureBox1.Image != null)
{
//Save First
Bitmap varBmp = new Bitmap(pictureBox1.Image);
Bitmap newBitmap = new Bitmap(varBmp);
varBmp.Save(savefilediag.FileName, ImageFormat.Png);
//Now Dispose to free the memory
varBmp.Dispose();
varBmp = null;
pictureBox1.Image = null;
pictureBox1.Invalidate();
}
else
{ MessageBox.Show("null exception"); }
}
}
You can use the Clone method to overwrite an instance of your picturebox's image with a subspace of the image.
Bitmap varBmp = new Bitmap(pictureBox1.Image);
varBmp = varBmp.Clone(new RectangleF(0, 0, 400, 400), varBmp.PixelFormat);
From there, you can go ahead and save it to a file.
varBmp.Save(savefilediag.FileName, ImageFormat.Png);

Refactor code - make class [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to make a class Photo where can I submit methods, because I will be use these methods many times in many pages.
So how can I send my image in parameter ?
Now I have :
PhotoChooserTask selectPhoto = null;
private void chooseLogoButton_Click(object sender, RoutedEventArgs e)
{
selectPhoto = new PhotoChooserTask();
selectPhoto.Completed += new EventHandler<PhotoResult>(selectPhoto_Completed);
selectPhoto.Show();
}
void selectPhoto_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
MessageBox.Show(e.ChosenPhoto.Length.ToString());
//Code to display the photo on the page in an image control named myImage.
System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
bmp.SetSource(e.ChosenPhoto);
logoQrCodeImage.Source = bmp;
}
}
And I made a class Photo:
public class Photo
{
PhotoChooserTask selectPhoto = null;
public void chooseLogo()
{
selectPhoto = new PhotoChooserTask();
selectPhoto.Completed += new EventHandler<PhotoResult>(selectPhoto_Completed);
selectPhoto.Show();
}
void selectPhoto_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
MessageBox.Show(e.ChosenPhoto.Length.ToString());
//Code to display the photo on the page in an image control named myImage.
System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
bmp.SetSource(e.ChosenPhoto);
logoQrCodeImage.Source = bmp; //ERROR
}
}
}
You could build your class to support Tasks and then use an async/await event handler. So your class would look like this:
public class PhotoChooser
{
public Task<BitmapImage> ChoosePhoto()
{
var taskSource = new TaskCompletionSource<BitmapImage>();
var chooser = new PhotoChooserTask();
chooser.Completed += (s, e) =>
{
if (e.ChosenPhoto == null)
{
taskSource.SetResult(null);
}
else
{
BitmapImage bmp = new BitmapImage();
bmp.SetSource(e.ChosenPhoto);
taskSource.SetResult(bmp);
}
};
chooser.Show();
return taskSource.Task;
}
}
The your event handler would look like this:
private async void ChoosePhoto_OnClick(object sender, RoutedEventArgs e)
{
var chooser = new PhotoChooser();
logoQrCodeImage.Source = await chooser.ChoosePhoto();
}
Update:
If you are using Windows Phone 7 you can still use async and await by adding the Async for Silverlight, .NET 4, Windows Phone NuGet Package. Just add a nuget reference and search for Async. It should be the first one.
You can supply a callback on what to do when the photo finishes selecting.
For example, you can add event to Photo class (you'd need to define class PhotoEventHandler too)
public class PhotoEventArgs
{
public Bitmap Bmp;
}
public event EventHandler<PhotoEventArgs> photoSelectCompleted;
and in the method invoke the event
void selectPhoto_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
MessageBox.Show(e.ChosenPhoto.Length.ToString());
//Code to display the photo on the page in an image control named myImage.
System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
bmp.SetSource(e.ChosenPhoto);
if (photoSelectCompleted != null)
photoSelectCompleted(this, new PhotoEventArgs(){ Bmp = bmp;});
}
}
and in the original page subscribe to the event and in the eventhandler do this:
void photoSelectCompleted(object sender, PhotoEventArgs e)
{
logoQrCodeImage.Source = e.Bmp;
}

C# Passing image on select from one page to another xaml page in WindowsPhone

Using Photochooser Task the image has to be loaded and passed immediately to another page. But shows blank when implemented the following code:
private void LoadPicture_Click(object sender, RoutedEventArgs e)
{
PhotoChooserTask photoChooserTask;
photoChooserTask = new PhotoChooserTask();
photoChooserTask.Completed += new EventHandler<PhotoResult>(photoChooserTask_Completed);
photoChooserTask.Show();
NavigationService.Navigate(new Uri("/Page1.xaml", UriKind.Relative));
}
void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
bmp.SetSource(e.ChosenPhoto);
Page1 p1 = new Page1();
p1.encodeImg.Source = bmp;
}
else
{
MessageBox.Show("Image Loading Failed.");
}
}
Please suggest in fixing the above the issue.
Thanks!
Have you solved it? if you haven't you could use something like this. in your photoChooseTask handler save the bitmapImage
PhoneApplicationService.Current.State["yourparam"] = bmp;
and then in your Page1 you get the bitmapImage
BitmapImage bitmapGet = PhoneApplicationService.Current.State["yourparam"] as BitmapImage;
here's how you should use this.
void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
bmp.SetSource(e.ChosenPhoto);
//save the bitmapImage
PhoneApplicationService.Current.State["yourparam"] = bmp;
}
else
{
MessageBox.Show("Image Loading Failed.");
}
NavigationService.Navigate(new Uri("/Page1.xaml", UriKind.Relative));
}
your Page1
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
//get the bitmapImage
BitmapImage bitmapGet = PhoneApplicationService.Current.State["yourparam"] as BitmapImage;
//set the bitmpaImage
img.Source = bitmapGet;
base.OnNavigatedTo(e);
}
More about PhoneApplicationService.Current.State :)
The navigation must be done after completed event, photochooser.show() suppresses the main application thread, hence you can only pass the image stream once you get it. So, shift navigation statement to completed event handler and using isolatedstoragesettings.applicationsettings to store the image and get it back on second page.
Another way to achieve it is to save the image in isolateStorage first and pass the file path to your page1 as a string parameter.
page1 then could load the image anytime it needs.

Categories