I am trying to take a picture using Camera class from Android.Hardware. I am getting the feed and the camera is getting auto-foucs. The problem is that I do not know how to take the photo.
_camera = Camera.Open();
Camera.Parameters param = _camera.GetParameters();
param.FocusMode = Camera.Parameters.FocusModeContinuousPicture;
_camera.SetParameters(param);
var previewSize = _camera.GetParameters().PreviewSize;
_textureView.LayoutParameters =
new FrameLayout.LayoutParams(previewSize.Width,
previewSize.Height, GravityFlags.Center);
try
{
_camera.SetPreviewTexture(surface);
_camera.StartPreview();
}
catch (Java.IO.IOException ex)
{
System.Console.WriteLine(ex.Message);
}
// this is the sort of thing TextureView enables
_textureView.Rotation = 90.0f;
This link may help you on this https://developer.xamarin.com/recipes/android/other_ux/camera_intent/take_a_picture_and_save_using_camera_app/
But you may use this code for taking picture (TakeAPicture).
private void TakeAPicture (object sender, EventArgs eventArgs)
{
Intent intent = new Intent (MediaStore.ActionImageCapture);
App._file = new File (App._dir, String.Format("myPhoto_{0}.jpg", Guid.NewGuid()));
intent.PutExtra (MediaStore.ExtraOutput, Uri.FromFile (App._file));
StartActivityForResult (intent, 0);
}
Happy Coding! :)
The TakePicture-method is the one you are looking for. To use this you need to implement some interfaces. Especially the IPictureCallback to receive the picture in OnPictureTaken.
A sample implementation would look like this:
public void OnPictureTaken(byte[] data, Android.Hardware.Camera camera)
{
camera.StopPreview();
Toast.MakeText(this, "Cheese", ToastLength.Short).Show();
camera.StartPreview();
}
To prevent that the app hangs you need to stop the preview and (re-)start it again.
Related
So I have a bit of a weird problem.
I've implemented a camera preview class (largely following this code here: https://learn.microsoft.com/en-us/samples/xamarin/xamarin-forms-samples/customrenderers-view/) but have added a button at the bottom to take a picture. This involves the use of both some xamarin forms code and some xamarin android code.
However, the CapturePage is only put on the stack when the user announces that they want to take a photo, and after the photo has been taken, I want to pop the Capture page to go back to the main screen. Currently, I have a static boolean value in the overall project that is changed from false to true when a capture has occurred. Is there some way to get my code in Main.xaml.cs to wait on this value changing, then pop whatever is on top of the navigation stack? Is this a use for a property changed? See code below:
The code in Project.Droid that handles the capturing and saving of the image:
void OnCapButtonClicked(object sender, EventArgs e)
{
// capButton.capture is an instance of Android.Hardware.Camera
capButton.capture.TakePicture(null, null, this);
// stop the preview when the capture happens
CameraInfoContainer.isPreviewing = false;
}
public void OnPictureTaken(byte[] data, Camera camera)
{
var filepath = string.Empty;
var clientInstanceId = Guid.NewGuid().ToString();
var saveLoc = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures);
filepath = System.IO.Path.Combine(saveLoc.AbsolutePath, clientInstanceId + ".jpg");
try
{
System.IO.File.WriteAllBytes(filepath, data);
//mediascan adds the saved image into the gallery
var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
mediaScanIntent.SetData(Android.Net.Uri.FromFile(new File(filepath)));
Forms.Context.SendBroadcast(mediaScanIntent);
}
catch (Exception e)
{
System.Console.WriteLine(e.ToString());
}
// CameraInfoContainer is a static class in Project NOT in Project.Droid
CameraInfoContainer.savedCapture = filepath;
CameraInfoContainer.capType = CaptureType.Photo;
CameraInfoContainer.captureComplete = true; // here is where I set the value (in Project)
}
Now the code in Project that pushes the capture page on the stack and that I want to trigger when the capture has happened:
// this method puts the capture page on the stack and starts the whole process
private async Task ExecuteNewCapture()
{
var cp = new CapturePage();
var np = new NavigationPage(cp);
await Navigation.PushModalAsync(np, true);
}
// this is the method that I want to trigger when a photo is taken (in Project/Main.xaml.cs)
private async Task Complete(string fileLoc)
{
await Navigation.PopModalAsync();
}
Answer is in a comment from Junior Jiang. Ended up using Xamarin.Forms.MessagingCenter to get done what I needed.
I've got a little problem with ZXing.net... I dosen't work !
Maybe I use it incorrectly, but I search, search, search, nothing seems to work... I use WindowsForms. I want to read my QR Code thought my camera. I use another library called AForge. This one works perfectly ; My camera shows up and works like a charm ! But when I want to read a QR Code, it dosen't work...
So maybe someone will be able to help me ... ?
//When I load my form, I start the camera
private void FrmConnexion_Load(object sender, EventArgs e)
{
// enumerate video devices
videoSources = new FilterInfoCollection(FilterCategory.VideoInputDevice);
// create video source
videoStream = new VideoCaptureDevice(videoSources[0].MonikerString);
// set NewFrame event handler
videoStream.NewFrame += new NewFrameEventHandler(videoSource_NewFrame);
// start the video source
videoStream.Start();
}
//Every new frame of the video
void videoSource_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
try
{
streamBitmap = (Bitmap)eventArgs.Frame.Clone();
safeTempstreamBitmap = (Bitmap)streamBitmap.Clone();
Pic_Camera.Image = streamBitmap;
Pic_Camera.Refresh();
//Where I decome my QR Code.
Result result = barcodeReader.Decode(streamBitmap);
//To see my result, I register my result into a Label.
Lbl_Identifiant.Text = "{result?.Text}";
}
catch (Exception exp)
{
Console.Write(exp.Message);
}
}
I think I didn't forget anything..
Thanks for your help !
How to upload or add an Image to UIImageView directly from iPhone/Ipad Captured camera Image.
I have uploaded an image to UIImageView from photo library.
Now, I want upload an image directly after taken an image through camera to ImageView.
Please suggest me how to implement this.
using IOS 8.0
This can be accomplished very easily with the Xamarin.Mobile component, which is free and works with all platforms.
http://components.xamarin.com/view/xamarin.mobile
From the example they give:
using Xamarin.Media;
// ...
var picker = new MediaPicker ();
if (!picker.IsCameraAvailable)
Console.WriteLine ("No camera!");
else {
try {
MediaFile file = await picker.TakePhotoAsync (new StoreCameraMediaOptions {
Name = "test.jpg",
Directory = "MediaPickerSample"
});
Console.WriteLine (file.Path);
} catch (OperationCanceledException) {
Console.WriteLine ("Canceled");
}
}
After you take the picture, it is saved to the directory you specified, with the name you specified. To easily retrieve this picture and display it with your ImageView using the above example you can do the following:
//file is declared above as type MediaFile
UIImage image = new UIImage(file.Path);
//Fill in with whatever your ImageView is
yourImageView.Image = image;
Edit:
Just a note that the above needs to be asynchronous. So if you want to launch the camera from a button call, for instance, you just slightly modify the .TouchUpInside event:
exampleButton.TouchUpInside += async (object sender, EventArgs e) => {
//Code from above goes in here, make sure you have async after the +=
};
Otherwise you could wrap the code from above in a function and add async to that:
public async void CaptureImage()
{
//Code from above goes here
}
You will need to use AVFoundation to do this. Check out the AVCam sample project in Xcode:
https://developer.apple.com/library/ios/samplecode/AVCam/Introduction/Intro.html
In my App you can open a Site where you can switch on and off the Flashlight.
The first time it works, but if I try to switch the flashlight on a second time the App crashes.
I think this is a Problem with AudioVideoCaptureDevice.OpenAsync. If I call it a second time the App crashes with a System.Reflection.TargetInvocationException WinRT-Informationen: Unable to acquire the camera. You can only use this class while in the foreground.
Someone know this Problem?
protected AudioVideoCaptureDevice Device { get; set; }
public Page10()
{
InitializeComponent();
}
async void tglSwitch_Checked(object sender, RoutedEventArgs e)
{
var sensorLocation = CameraSensorLocation.Back;
if (this.Device == null)
{
// get the AudioVideoCaptureDevice
this.Device = await AudioVideoCaptureDevice.OpenAsync(sensorLocation,
AudioVideoCaptureDevice.GetAvailableCaptureResolutions(sensorLocation).First());
}
var supportedCameraModes = AudioVideoCaptureDevice
.GetSupportedPropertyValues(sensorLocation, KnownCameraAudioVideoProperties.VideoTorchMode);
if (supportedCameraModes.ToList().Contains((UInt32)VideoTorchMode.On))
{
this.Device.SetProperty(KnownCameraAudioVideoProperties.VideoTorchMode, VideoTorchMode.On);
// set flash power to maxinum
this.Device.SetProperty(KnownCameraAudioVideoProperties.VideoTorchPower,
AudioVideoCaptureDevice.GetSupportedPropertyRange(sensorLocation, KnownCameraAudioVideoProperties.VideoTorchPower).Max);
this.tglSwitch.Content = "Light on";
this.tglSwitch.SwitchForeground = new SolidColorBrush(Colors.Green);
}
}
void tglSwitch_Unchecked(object sender, RoutedEventArgs e)
{
var sensorLocation = CameraSensorLocation.Back;
sensorLocation = CameraSensorLocation.Back;
var supportedCameraModes = AudioVideoCaptureDevice
.GetSupportedPropertyValues(sensorLocation, KnownCameraAudioVideoProperties.VideoTorchMode);
if (this.Device != null && supportedCameraModes.ToList().Contains((UInt32)VideoTorchMode.Off))
{
this.Device.SetProperty(KnownCameraAudioVideoProperties.VideoTorchMode, VideoTorchMode.Off);
this.tglSwitch.Content = "Light off";
}
}
I would recommend to initialize the camera with OpenAsync ONE TIME in page lifecycle, for example in OnNavigatedTo event. And only makeSetProperty() methods calls code in your checkbox events to control light. It is also very important to dispose camera correctly then leaving the page, for example in OnNavigatedFrom event, by calling device.Dispose(). This option also make your flashlight to work faster.
Keep in mind that Windows Phone 8.1 now has dedicated API for torch, which works great and the code is more beautiful. You can use in Silverlight project as well, but you have to migrate your project. Here is more about this http://developer.nokia.com/community/wiki/Using_the_camera_light_in_Windows_Phone_7,_8_and_8.1 and https://msdn.microsoft.com/en-us/library/windows/apps/windows.media.devices.torchcontrol.
I an new in emgu cv c#. I want to create a camera only for simple photocapture from my laptop camera and other camera device connected to my laptop.I dont want video capture only simple photo capture.with one start and one capture button.and will save in particular location.helped would be appreciable.
namespace camera
{
public partial class cameracaps : Form
{
Capture capturecam=null;
bool capturingprocess=false;
Image<Bgr,Byte>imgOrg;
Image<Gray,Byte>imgproc;
public cameracaps()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
Capture cam = new Capture();
}
catch (NullReferenceException exception)
{
MessageBox.Show(exception.Message);
return;
}
Application.Idle += new EventHandler(processFunction);
capturingprocess=true;
}
void processFunction(object sender,EventArgs e)
{
imgOrg=capturecam.QueryFrame();
if(imgOrg ==null)return;
imgproc=imgOrg.InRange(new Bgr(50,50,50),new Bgr(250,250,250));
imgproc = imgproc.SmoothGaussian(9);
original.Image=imgOrg;
processed.Image=imgproc;
}
private void Button1_Click(object sender, EventArgs e)
{
if(capturingprocess==true)
{
Application.Idle-=processFunction;
capturingprocess = false;
Button1.Text="play";
}
else
{
Application.Idle+= processFunction;
capturingprocess= true;
Button1.Text="pause";
}
}
}
}
showing..The type initializer for 'Emgu.CV.CvInvoke' threw an exception. error..indicating error in
Capture cam = new Capture();
help me.
This is one of the biggest problem almost all the time we face in emgu cv.First of all copy dll file name opencv_core290.dll,open_cvhighgui290.dll to your project bin,try to use dependency tracker for dll files.Install dependency from this link-http://www.emgu.com/wiki/index.php/Download_And_Installation..If its not work then you should understand that application is getting connection with camera.Then go to My computer->right click->property->advanced system setting->system property->advance->environment variables->system variables->path->edit->and paste C:\Emgu\emgucv-windows-universal-cuda 2.9.0.1922\bin.and press ok.restart your system and it will work.