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
Related
I am trying to make a page (lets call it page #2) within my Xamarin.Android app that has a button, when you press on that button the camera app opens. Then you take a picture, accept the picture you took, and then you should be brought back to the page that originally had the camera button on it (page #2), and the image you took will be displayed there under the button.
The problem is that my overridden OnActivityResult() method never gets called after you accept the picture. You press the button, the camera app opens, you take a picture, accept the picture, the camera app closes and you are brought back to the page BEFORE the camera button page (so you're on page #1 now). I think the camera app itself is crashing? I am not sure how to find those logs. Sometimes a popup will show that says "Unfortunately, the camera has stopped." I am guessing that it is the way I am trying to save the photo taken to the phone itself? The only errors I have seen are within the device log, and occasionally it will throw a permission error saying I dont have access to write to the storage device on the phone, but I have the "write" permissions in the manifest file. I am targeting API 26.
Any ideas?
Here is the method for clicking the button:
private int PIC_REQUEST_CODE = 1;
private ImageView imageView;
private Java.IO.File image;
private void Button_Click(object sender, EventArgs e)
{
Intent takePictureIntent = new Intent(MediaStore.ActionImageCapture);
if (takePictureIntent.ResolveActivity(PackageManager) != null)
{
try
{
// Create an image file name
string timeStamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
string imageFileName = "JPEG_" + timeStamp + "_";
Java.IO.File storageDir = GetExternalFilesDir(global::Android.OS.Environment.DirectoryPictures);
Java.IO.File image = Java.IO.File.CreateTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
global::Android.Net.Uri photoURI = FileProvider.GetUriForFile(ApplicationContext, PackageName + ".fileprovider", image);
takePictureIntent.PutExtra(MediaStore.ExtraOutput, photoURI);
takePictureIntent.AddFlags(ActivityFlags.GrantWriteUriPermission);
StartActivityForResult(takePictureIntent, PIC_REQUEST_CODE);
}
catch (Exception ex)
{
//Not sure what to do, but here's a break point at least.
Toast.MakeText(this, "blah blah something went wrong", ToastLength.Short).Show();
}
}
}
And here is my simple OnActivityResult that gets skipped/ never called:
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
if (requestCode == PIC_REQUEST_CODE && resultCode == Result.Ok)
{
Bitmap bitmap = (Bitmap)data.Extras.Get("data");
imageView.SetImageBitmap(bitmap);
}
}
I figured out the current issue of the OnActivityResult() not being called. At the top above the class I was declaring
[Activity(Label = "#string/page_name", ScreenOrientation = ScreenOrientation.Portrait, NoHistory = true)]
The important note here is the "NoHistory=True" apparently that makes the page exit and return back to the previous page. Deleting the "NoHistory=true" worked and made it so the OnActivityResult() gets called. Some documentation about it says "A value of 'true' means that the activity will not leave a historical trace. It will not remain in the activity stack for the task, so the user will not be able to return to it" so I guess that makes sense.
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 have a canvasControl,in that CreateResources Event is fired only once when I run the Program.I had a FilePicker to pick an image source from local.Whenever an Image is Picked , i need to Call CreateResources event to load the Resources and then draw it using canvasBitmap and DrawingSession.
I Know how to Draw but,I Don't Know how to Load Resources Whenever an image is picked.Can anyone Suggest me ,how to achieve this??
It's not necessary to load resources in CreateResource event all the time, you can load resources whenever you want (outside of Draw event handler) and then just call Invalidate method. Look at this:
CanvasBitmap btmp;
private async void LoadNecessaryResourcesAndDraw()
{
btmp = await CanvasBitmap.LoadAsync(MyCanvasControl, "some_image.png");
MyCanvasControl.Invalidate(); /// this will invoke the draw event
}
public void MyCanvasControl_Draw(CanvasControl sender, CanvasDrawEventArgs args)
{
if(btmp != null)
{
args.DrawingSession.DrawImage(btmp);
}
}
Now you can call the LoadNecessaryResourcesAndDraw() method anytime. It will load the image asynchronously, then invoke the draw event which will draw the image.
in Win2D, the CreateResource event is only triggered when the CanvasControl is loading, that is, it will only be triggered once.
If you need to create resources after this, you need to create a custom LoadResourcesForLevelAsync method:
async Task LoadResourcesForLevelAsync(CanvasControl resourceCreator, int level)
{
levelBackground = await CanvasBitmap.LoadAsync(resourceCreator, ...);
levelThingie = await CanvasBitmap.LoadAsync(resourceCreator, ...);
// etc.
}
This is explained in the Win2D documentation, please refer to this document:
Loading resources outside of CreateResources
Update
A simple example of loading pictures in the Draw event:
private string imageFilePath = #"ms-appx:///Assets/StoreLogo.png";
private CanvasBitmap img;
private void CanvasControl_Draw(CanvasControl sender, CanvasDrawEventArgs args)
{
if (img != null)
{
args.DrawingSession.DrawImage(img);
}
else
{
GetImage().Wait();
}
async Task GetImage()
{
await Task.Run(async () =>
{
img = await CanvasBitmap.LoadAsync(sender, new Uri(imageFilePath));
}).ConfigureAwait(false);
}
}
Thanks.
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 !
I am trying to write a practice Drag and Drop program.
This program will display a picture (JPG or PNG or Bitmap) when one is dropped on it. It will play a music file when dropped on it and it will play a video when a video file is dropped on it.
I would like the drop Icon to indicate what kind of file is about to be dropped when the DragOver event is fired. And if the file type is not compatible with my program I want the Icon to be able to indicate that as well.
I have been going through the DragEventArgs class for weeks trying to figure out a way of being able to tell the difference between the 3 types of media file but I have come up empty. Can anyone help with this?
You can use the DragUIOverride to customize the look of the dragged object.
You can set it with the DragOver event on the target element:
private async void Grid_DragOver(object sender, DragEventArgs e)
{
e.DragUIOverride.Caption = "Some caption";
e.DragUIOverride.IsCaptionVisible = true;
e.DragUIOverride.IsContentVisible = true;
e.DragUIOverride.IsGlyphVisible = true;
e.AcceptedOperation = DataPackageOperation.Copy;
//check the type of the file
var items = await e.DataView.GetStorageItemsAsync();
if (items.Any())
{
var storageFile = items[0] as StorageFile;
if ( storageFile.FileType == ".jpg" )
{
e.DragUIOverride.SetContentFromBitmapImage(
new BitmapImage(new Uri("ms-appx:///Assets/jpgIcon.png")));
}
else if ( storageFile.FileType == "png" )
{
e.DragUIOverride.SetContentFromBitmapImage(
new BitmapImage(new Uri("ms-appx:///Assets/pngIcon.png")));
}
//...
else
{
//for disallowed file types
e.AcceptedOperation = DataPackageOperation.None;
e.DragUIOverride.SetContentFromBitmapImage(
new BitmapImage(new Uri("ms-appx:///Assets/errorIcon.png")));
}
}
}