WriteableBitmapExtension crashes app on device - windows-phone-8.1

I have added a WriteableBitmapExtension via NuGet to my Windows Phone 8.1 WinRT app. I have functions to capture an image from camera and save it to picture library. I tried rotate captured image before save and I found solution here
WriteableBitmap crashes program with no message?. Everything works fine on emulator but when I run my app on Nokia Lumia 630 it crashes few seconds after taking a photo without debbuger message. Can anyone help me with this issue? Here is my code of taking photo:
public WriteableBitmap Image
{
get
{
return this.image;
}
set
{
this.image = value;
this.RaisePropertyChanged(() => this.Image);
}
}
private async void TakePhoto()
{
using (var stream = new InMemoryRandomAccessStream())
{
var imgEncodingProperties = ImageEncodingProperties.CreateJpeg();
var img = BitmapFactory.New(640, 480);
await this.MediaCapture.CapturePhotoToStreamAsync(imgEncodingProperties, stream);
stream.Seek(0);
img.SetSource(stream);
WriteableBitmapExtensions.DrawLine(img, 10, 10, 300, 300, Colors.Black);
this.Image = img.Rotate(90);
this.TurnOffCaptureMode();
}
}
private void TurnOffCaptureMode()
{
this.MediaCapture.StopPreviewAsync();
this.IsInCaptureMode = false;
}

Alternate solution is here.
1 Open file Picket use build in camera to take picture.
var openPicker = new FileOpenPicker();
openPicker.ContinuationData["Action"] = "SendPicture";
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".png");
openPicker.PickSingleFileAndContinue();
***2. In app.xaml.cs you will get captured image. as below.***
public void Continue(IContinuationActivatedEventArgs args)
{
if(args.Kind == ActivationKind.PickFileContinuation)
{
var openPickerContinuationArgs = args as FileOpenPickerContinuationEventArgs;
// Recover the "Action" info we stored in ContinuationData
string action = (string) openPickerContinuationArgs.ContinuationData["Action"];
if(openPickerContinuationArgs.Files.Count > 0)
{
// TODO: Get the files here
}
else
{
// TODO: Write code here to handle picker cancellation.
}
}
}

Related

Exception When Rendering an Image Using Lumia Imaging SDK

In my WP8.1 app, I'm trying to crop an image using the Lumia (formerly Nokia) Imaging SDK. the image is retrieved using FileOpenPicker:
public async void ContinueFileOpenPicker(Windows.ApplicationModel.Activation.FileOpenPickerContinuationEventArgs args) {
if (args.Files.Count > 0) {
_stream = await args.Files[0].OpenAsync(Windows.Storage.FileAccessMode.Read);
_bitmapImage = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
await _bitmapImage.SetSourceAsync(_stream);
SelectedImage.Source = _bitmapImage;
}
else {
Debug.WriteLine("Operation cancelled.");
}
}
Then the filter applied in a button handler (after the user selected a cropping area; dimensions just for testing purposes):
private async void GetImageAcceptButton_Click(object sender, RoutedEventArgs e) {
await GetCroppedBitmapAsync();
}
async public Task GetCroppedBitmapAsync() {
using (var source = new RandomAccessStreamImageSource(_stream)) {
using (var filterEffect = new FilterEffect(source)) {
var filter = new CropFilter(new Windows.Foundation.Rect(0, 0, 100, 100));
filterEffect.Filters = new IFilter[] { filter };
var target = new WriteableBitmap(50, 50);
using (var renderer = new WriteableBitmapRenderer(filterEffect, target)) {
await renderer.RenderAsync();
SelectedImage.Source = target;
}
}
}
}
The RenderAsync() call throws an exception:
System.Runtime.InteropServices.COMException occurred
HResult=-2147467259
Message=Error HRESULT E_FAIL has been returned from a call to a COM component.
Source=mscorlib
ErrorCode=-2147467259
Applying the filters seems rather straightforward. Why does it fail here?
You should enable native debugging and look at the Output window. You're currently missing the real exception message (which tries to be more specific). Exception message strings are "smuggled" across the WinRT call border, only an HRESULT is officially passed (here, E_FAIL).
Is this Silverlight 8.1 or a Universal App btw?
My guess at an answer might be that you need to seek/rewind the stream back. It could be that the position is at the end.

CameraPreviewImageSource empty preview frame

I made cut and paste of the code below about how to use CameraPreviewImageSource and access to preview buffer frames, but do not work and it seems the frame buffer size is 0x0 reading the value of IImageSize parameter of OnPreviewFrameAvailable event.
How to get preview buffer of MediaCapture - Universal app
protected override void OnNavigatedTo(NavigationEventArgs e)
{
InitializeAsync();
}
public async void InitializeAsync()
{
_cameraPreviewImageSource = new CameraPreviewImageSource();
await _cameraPreviewImageSource.InitializeAsync(string.Empty);
var properties = await _cameraPreviewImageSource.StartPreviewAsync();
var width = 640.0;
var height = 480;
_writeableBitmap = new WriteableBitmap((int)width, (int)height);
_writeableBitmapRenderer = new WriteableBitmapRenderer(_cameraPreviewImageSource, _writeableBitmap);
Initialized = true;
_cameraPreviewImageSource.PreviewFrameAvailable += OnPreviewFrameAvailable;
}
private async void OnPreviewFrameAvailable(IImageSize args)
{
System.Diagnostics.Debug.WriteLine("ww:"+args.Size.Width+" hh:"+args.Size.Height);
// Prevent multiple rendering attempts at once
if (Initialized && !_isRendering)
{
_isRendering = true;
try
{
await _writeableBitmapRenderer.RenderAsync();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("\n\n"+ex.Message);
System.Diagnostics.Debug.WriteLine(ex.StackTrace);
}
_isRendering = false;
}
}
Capabilities (webcam & microphone) on Package.appxmanifest has been selected
Implementing CameraPreviewImageSource on a Silverlight app works great!
I am afraid you are (were) seeing a bug in Lumia Imaging SDK 2.0.184. The problem only occured on some camera models and only on 8.1/universal applications. Silverlight applications were not affected by the problem.
The bug has been fixed in the newly released Lumia Imaging SDK 2.0.208. From release notes:
Fixed ArgumentOutOfRangeException being thrown by CameraPreviewImageSource when used with certain camera models.

Display splash page only on the 1st launch, or after a crash or a kill of the app

Could you please explain how to display splash page when only first launch or crash or kill the app in windows phone.
You could use the IsolatedStorage to check if the app was opened before or not
private static bool hasSeenIntro;
/// <summary>Will return false only the first time a user ever runs this.
/// Everytime thereafter, a placeholder file will have been written to disk
/// and will trigger a value of true.</summary>
public static bool HasUserSeenIntro()
{
if (hasSeenIntro) return true;
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!store.FileExists(LandingBitFileName))
{
// just write a placeholder file one byte long so we know they've landed before
using (var stream = store.OpenFile(LandingBitFileName, FileMode.Create))
{
stream.Write(new byte[] { 1 }, 0, 1);
}
return false;
}
hasSeenIntro = true;
return true;
}
}
For the crash system, you could use BugSense for Windows Phone

Infinite wait loading remote image into BitmapImage() in Background Agent

I have a valid URL for a remote JPEG which I'm trying to load in the background. But I find I never get control back after invoking the BitmapImage() constructor. My question is, should this approach work, or should I pitch it all, load up BcpAsync project from NuGet and start working with WebClient asynch methods?
A sample URL for which it fails is
http://image.weather.com/images/maps/current/garden_june_720x486.jpg
It is valid. .UpdateAsync() references it from AppViewModel.Instance, it's not explicitly referenced here.
Here's the background agent:
protected override async void OnInvoke(ScheduledTask task)
{
AppViewModel.LoadData();
await AppViewModel.Instance.RemoteImageProxy.UpdateAsync();
AppViewModel.Instance.ImageUrl = AppViewModel.Instance.RemoteImageProxy.LocalFileUri;
AppViewModel.Instance.UpdateCount++;
PinnedTile.Update();
}
AppViewModel.SaveData();
#if DEBUG
ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(AppViewModel.Instance.BgAgentInterval));
#endif
NotifyComplete();
}
Here's the invoked method:
public Task<double> UpdateAsync() {
LastCheckedTime = DateTime.UtcNow;
CompletionTask = new TaskCompletionSource<double>();
// Not usually called on UI thread, not worth optimizing for that case here.
Deployment.Current.Dispatcher.BeginInvoke(() => { //todo determine whether System.Windows.Deployment.Dispatcher can be called from main app, or just bgAgent.
HelperImageControl = new Image();
HelperImageControl.Loaded += im_Loaded;
HelperImageControl.ImageFailed += im_ImageFailed;
HelperImageControl.ImageOpened += im_ImageOpened;
// breakpoint here
HelperImageControl.Source = new BitmapImage(SourceUri);
// stepping over the function, control does not return here. Nor are any of the above events fired.
});
return CompletionTask.Task; // this will be completed in one of the subsequent control events...
}
You need to call CompletionTask.SetResult(); to return control back to the caller method.
This works (I'm returning 100 in case of successful download because you set the task to return double).
TaskCompletionSource<double> CompletionTask;
public Task<double> UpdateAsync()
{
CompletionTask = new TaskCompletionSource<double>();
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
var HelperImageControl = new Image();
var bmp = new BitmapImage();
bmp.ImageOpened += bmp_ImageOpened;
bmp.ImageFailed += bmp_ImageFailed;
bmp.CreateOptions = BitmapCreateOptions.None;
bmp.UriSource = new Uri("http://image.weather.com/images/maps/current/garden_june_720x486.jpg", UriKind.Absolute);
HelperImageControl.Source = bmp;
});
return CompletionTask.Task;
}
void bmp_ImageFailed(object sender, ExceptionRoutedEventArgs e)
{
CompletionTask.SetException(e.ErrorException);
}
void bmp_ImageOpened(object sender, RoutedEventArgs e)
{
CompletionTask.SetResult(100);
}

save the image in storage file in windows phone 8

I'm making a windows phone 8 app of an app I made for windows store, and I am using PhotoChooser task to let the user upload a profile picture.
In the store version i used streams and FileOpenPicker, but i don't know how to use streams with PhotoChooser task.
This is how i did it in windows store, and its perfect:
StorageFile image;
public bunForm()
{
image = null;
this.InitializeComponent();
}
private async void choosePic(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.ViewMode = PickerViewMode.Thumbnail;
// Filter to include a sample subset of file types
openPicker.FileTypeFilter.Clear();
openPicker.FileTypeFilter.Add(".bmp");
openPicker.FileTypeFilter.Add(".png");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".jpg");
// Open a stream for the selected file
var file = await openPicker.PickSingleFileAsync();
if (file != null)
{
image = file;
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
bunPic.Visibility = Visibility.Visible;
// Ensure a file was selected
if (file != null)
{
// Ensure the stream is disposed once the image is loaded
using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
// Set the image source to the selected bitmap
BitmapImage bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(fileStream);// bitmapImage.UriSource.ToString();
bunPic.Source = bitmapImage;
}
}
}
}
And here is how i'm trying it at windows Phone 8:
But (openPicker.PickSingleFileAsync();) line gives me error.
public BunForm()
{
InitializeComponent();
image = null;
this.photoChooserTask = new PhotoChooserTask();
this.photoChooserTask.Completed += new EventHandler<PhotoResult>(photoChooserTask_Completed);
}
StorageFile image;
private void choosePic(object sender, RoutedEventArgs e)
{
photoChooserTask.Show();
}
private async void photoChooserTask_Completed(object sender, PhotoResult e)
{
//this is the only line that gives me error
var file = await openPicker.PickSingleFileAsync();
///
if (file != null)
{
image = file;
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
if (file != null)
{
// Ensure the stream is disposed once the image is loaded
using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
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);
myImage.Source = bmp;
}
}
}
Debug.WriteLine("pic done");
}
I was wondering how i can save the image in storage file in windows phone 8?
As noted on MSDN pages - OpenFilePicker cannot be used in C# WP8 apps, but you can use the PhotoChooserTask with ease for uploadng the profile picture:
// first invoke the task somewhere
PhotoChooserTask task = new PhotoChooserTask();
task.Completed += task_Completed;
task.Show();
// handle the result
async void task_Completed(object sender, PhotoResult e)
{
// no photo selected
if (e.ChosenPhoto == null) return;
// get the file stream and file name
Stream photoStream = e.ChosenPhoto;
string fileName = Path.GetFileName(e.OriginalFileName);
// persist data into isolated storage
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
using (Stream current = await file.OpenStreamForWriteAsync())
{
await photoStream.CopyToAsync(current);
}
...
// how to read the data later
StorageFile file2 = await ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
Stream imageStream = await file2.OpenStreamForReadAsync();
// display the file as image
BitmapImage bi = new BitmapImage();
bi.SetSource(imageStream);
// assign the bitmap to Image in XAML: <Image x:Name="img"/>
img.Source = bi;
}
Accoriding to this
Windows Phone 8
This API is supported in native apps only.
You can't use FileOpenPicker class.
There are already answers to the problem OpenFilePicker not working