enter code hereI'm trying to create an app to take photos, the problem is when I try to save the photo in an internal folder of the app. Photos selected from gallery do not corrupt, but those taken by camera corrupt
CS:
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class CameraPage : ContentPage
{
public CameraPage()
{
InitializeComponent();
}
async void EscolherIMG(System.Object sender, System.EventArgs e)
{
var result = await MediaPicker.PickPhotoAsync(new MediaPickerOptions
{
Title = "Por favor uma imagem"
});
var stream = await result.OpenReadAsync();
resultIMG.Source = ImageSource.FromStream(() => stream);
}
async void TirarFT(System.Object sender, System.EventArgs e)
{
var result = await MediaPicker.CapturePhotoAsync();
var stream = await result.OpenReadAsync();
var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
Directory = "Fotos Tiradas",
Name = "Foto.jpeg"
});
}
}
Related
I am building a camera application in Xamarin.Forms with a custom renderer.
Android.
I want to emit a shutter sound when the camera shutter button is pressed.
Currently, I have the TalkePhotoButtonClickedHandler as shown below.
private async void TakePhotoButtonClickedHandler(object sender, EventArgs e)
{
if (this.imageAvailableListener == null)
{
this.imageAvailableListener = new ImageAvailableListener(this);
}
var bitmap = this.texture.Bitmap;
CameraManager manager = (CameraManager)MainActivity.context.GetSystemService(Context.CameraService);
try
{
CameraCharacteristics characteristics = manager.GetCameraCharacteristics(this.device.Id);
StreamConfigurationMap map = characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap) as StreamConfigurationMap;
Size[]? jpegSize = map.GetOutputSizes((int)ImageFormatType.Jpeg);
int ww = jpegSize[0].Width;
int hh = jpegSize[0].Height;
ImageReader reader = ImageReader.NewInstance(ww, hh, ImageFormatType.Jpeg, 1);
List<Surface> outputSurfaces = new List<Surface>(2);
outputSurfaces.Add(reader.Surface);
outputSurfaces.Add(new Surface(this.texture.SurfaceTexture));
CaptureRequest.Builder captureBuilder = this.device.CreateCaptureRequest(CameraTemplate.StillCapture);
captureBuilder.AddTarget(reader.Surface);
captureBuilder.Set(CaptureRequest.ControlMode, (int)ControlMode.Auto);
reader.SetOnImageAvailableListener(imageAvailableListener, backgroundHandler);
var sessionListener = new CameraSessionCallback(this);
this.device.CreateCaptureSession(
outputSurfaces,
new CameraStateCallback(captureBuilder, sessionListener, this.backgroundHandler),
this.backgroundHandler
);
}
catch (CameraAccessException ex)
{
throw ex;
}
}
It looks like I should write the shutter callback here.
private Camera.ShutterCallback mShutterListener =
new Camera.ShutterCallback() {
public void onShutter() {
// empty OK。
}
};
private Camera.PictureCallback mPictureListener =
new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
}
};
I found the Java code, but how can I write it in C#?
I use Xamarin.Essentials: Media Picker to take photo, a shutter sound when the camera shutter button is pressed.
<StackLayout>
<Image x:Name="PhotoImage" />
<Button
x:Name="takephoto"
Clicked="takephoto_Clicked"
Text="take photo" />
</StackLayout>
private async void takephoto_Clicked(object sender, EventArgs e)
{
var result = await Xamarin.Essentials.MediaPicker.CapturePhotoAsync();
if (result != null)
{
var stream = await result.OpenReadAsync();
takephoto.ImageSource = ImageSource.FromStream(() => stream);
}
}
I'm trying to get my user to pick a photo from the gallery (this code works works fine) then upload this picture to firebase storage. Once the code hits UploadPetProfileImage() the app enters breakpoint and I get the following error: : 'Exception occured while processing the request.
I'm unable to see what is wrong with code below:
FirebaseStorageHelper.cs
public async Task<string> UploadPetProfileImage(Stream fileStream, string fileName)
{
var imageUrl = await firebaseStorage
.Child("PetProfileImages")
.Child(fileName)
.PutAsync(fileStream);
return imageUrl;
}
AddPetPage:
FirebaseStorageHelper firebaseStorageHelper = new FirebaseStorageHelper();
private async void AddPetImage_Clicked(object sender, EventArgs e)
{
var pickResult = await FilePicker.PickAsync(new PickOptions
{
FileTypes = FilePickerFileType.Images,
PickerTitle = "Pick an Image of your Dog!"
});
if(pickResult != null)
{
var stream = await pickResult.OpenReadAsync();
PetImage.Source = ImageSource.FromStream(() => stream);
PetImageFileName = pickResult.FileName;
AddPetImageBtn.IsVisible = false;
await firebaseStorageHelper.UploadPetProfileImage(stream, pickResult.FileName);
}
}
I was able to reproduce this issue:
Please check the connection to your Firebase Storage.
Do not use the gs://xamarinfirebasestorage-xxxxx.appspot.com. Use xamarinfirebasestorage-xxxxx.appspot.com instead.
FirebaseStorage firebaseStorage = new FirebaseStorage("xamarinfirebasestorage-xxxxx.appspot.com");
I am trying to drag an image from WPF application to UWP application but getting this error
"invalid formatetc structure (exception from hresult: 0x80040064 (dv_e_formatetc)) in GetStorageItemsAsync method"
public async void OnFileDrop(object sender, DragEventArgs e)
{
List<StorageFile> dropFiles = new List<StorageFile>();
if (e.DataView.Contains(StandardDataFormats.StorageItems))
{
var items = await e.DataView.GetStorageItemsAsync();
var isShow2GBMessage = false;
var isShowEXEerrorMessage = false;
if (items.Count > 0)
{
foreach (var appFile in items.OfType<StorageFile>())
{
BasicProperties filesize = await appFile.GetBasicPropertiesAsync();
var fileSize = filesize.Size;
CheckAndAddFiles(dropFiles, ref isShow2GBMessage, ref isShowEXEerrorMessage, appFile, fileSize);
}
}
UploadFiles(dropFiles);
}
}
When I drag the image it is getting copied into a folder but how do I get the path address using DragEventArgs?
I have three pages, I enter the data on the second page and transfer it to page number one, returning to it at the same time, there is no problem with this, I use navigation, like this:
private async void OnSaveTitleButtonCliked(object sender, EventArgs e)
{
var title_data = new LabelViewModel
{
Label = editor.Text,
Date = DateTime.Now
};
var mainpage = new MainPage();
mainpage.BindingContext = title_data;
await Navigation.PushAsync(mainpage);
}
But I also need to transfer this data to page number three, so that I can go there from the first page and see, I tried the mvvm, but so far I have not understood how it works.
Please tell me how to do it better:)
Pass data by constructor:
In Page1:
private async void GoToPage2(object sender, EventArgs e)
{
var title_data = new LabelViewModel
{
Label = editor.Text,
Date = DateTime.Now
};
//Pass the model here
var Page2 = new Page2(title_data);
await Navigation.PushAsync(Page2);
}
In Page2:
public partial class Page2 : ContentPage
{
public LabelViewModel model;
public Page2(LabelViewModel m) {
InitializeComponent();
this.model = m;
//You can use your model here
}
}
Pass data by public property:
In Page1:
private async void GoToPage2(object sender, EventArgs e)
{
var title_data = new LabelViewModel
{
Label = editor.Text,
Date = DateTime.Now
};
var Page2 = new Page2();
//Pass the model here
Page2.model = title_data;
await Navigation.PushAsync(Page2);
}
In Page2:
public partial class Page2 : ContentPage
{
public LabelViewModel model;
public Page2()
{
InitializeComponent();
//You can use your model here
Console.WriteLine(model.Label);
Console.WriteLine(model.Date);
}
}
Let me know if you have any questions.
I'll let some examples here
On the first page (who calls the second one)
private async void MenuLista(object sender, EventArgs e)
{
var item = (ModelosPPP)((Button)sender).BindingContext;
if (PopupRunnning != false)
return;
var page = new MenuListSV(item);
PopupRunnning = true;
page.Action += async (a, b) =>
{
switch (b)
{
case 1:
await DisplayAlert("PDF", null, "ok");
break;
case 2:
await DisplayAlert("Reenviar", null, "ok");
break;
case 3:
await DisplayAlert("Excluir", null, "ok");
break;
}
};
page.Disappearing += (c, d) =>
{
PopupRunnning = false;
};
await PopupNavigation.Instance.PushAsync(page);
}
in Second Page
public partial class MenuListSV : PopupPage
{
public MenuListSV(Models.ModelosPPP obj)
{
InitializeComponent();
BindingContext = obj;
}
public EventHandler<int> Action;
public async void MenuChoice(object sender, EventArgs e)
{
var btn = sender as Button;
switch (btn.Text)
{
case "Abrir PDF":
Action?.Invoke(this, 1);
break;
case "Reenviar":
Action?.Invoke(this, 2);
break;
case "Excluir":
Action?.Invoke(this, 3);
break;
}
await PopupNavigation.Instance.PopAsync();
}
}
I've recently upgraded my WP7 app to Mango and am having some problems with the camera. The code below used to work on 7.0, but on 7.1 the completed handler fires before the dialog is even shown, so I can't capture the result. After taking the photo, the phone displays "Resuming..." which it never used to do.
var dlg = new CameraCaptureTask();
dlg.Completed += (s, e) =>
{
if (e.TaskResult == TaskResult.OK) {
BitmapImage bmp = new BitmapImage();
bmp.SetSource(e.ChosenPhoto);
//var img = new Image();
//img.Source = bmp;
string caption = string.Empty;
var inputDialog = new InputPrompt()
{
Title = "Caption",
Message = "Enter caption/description for snapshot",
};
inputDialog.Completed += (ss, ee) =>
{
if (ee.PopUpResult == PopUpResult.Ok)
{
caption = ee.Result;
var snap = SnapshotBLL.AddSnapshot(recipeId, bmp, caption);
onComplete(null, new SnapshotEventArgs(snap));
}
};
inputDialog.Show();
}
};
dlg.Show();
The MSDN docs appear to show a variation of my code but I can no longer get the result of the camera capture task.
Assuming that your sample comes from a single method I wouldn't expect it to ahve worked pre Mango.
The CameraCaptureTask should be created and the callback assigned in the constructor of the page for it to work properly.
Something like:
public partial class MainPage : PhoneApplicationPage
{
private CameraCaptureTask cct = new CameraCaptureTask();
public MainPage()
{
InitializeComponent();
cct.Completed += new EventHandler<PhotoResult>(cct_Completed);
}
private void cct_Completed(object sender, PhotoResult e)
{
// Do whatever here
}
private void SomeEventHandler(object sender, RoutedEventArgs e)
{
cct.Show();
}
}
This works in both 7.0 & 7.1