CameraPreviewImageSource empty preview frame - windows-phone-8.1

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.

Related

Reading data from Arduino Bluetooth on Windows Phone 8.1

I am developing a code that will allow me to send small amounts of data between my arduino mega and my windows 8.1 phone using a HC-05 bluetooth module.
Sending data from the phone to the arduino was pretty simple, but I am having a dire time attempting to read data that comes back from the arduino that I send on the serial port.
For testing purposes my code is simple, sending ascii charaters 'a' & 'b' to turn an LED on & off, this could not work any better, but I am having trouble trying to figure out how to correctly read the data that I send back to my phone.
I send a single arbitrary ascii character back to the phone but I cannot for the life of me figure out the correct way of reading this data from the bluetooth stream I have setup.
I have been trying for nearly two days, but everything I try ends up freezing my phone with no exceptions thrown? A lot of posts online send me to the Nokia dev site which is now inactive.
I have tried using the 'datareader' and the 'streamreader' classes to do this but it always freezes, does anyone know how to make this work? And why my streamreader keeps freezing my phone?
I have tried to annotate my code appropriatley (seen below). The problem occurs in the 'Tick' event handler at the bottom of the code.
(FYI: All capabilities have been added to the manifest files so this shouldn't be the problem).
Thank you.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Bluetooth_SL.Resources;
using Windows.Networking;
using Windows.Networking.Proximity;
using Windows.Networking.Sockets;
using Windows.Devices.Bluetooth;
using System.IO;
using Microsoft.Xna.Framework;
using System.Windows.Threading;
using Windows.Storage.Streams; // <-- for the datareader class
namespace Bluetooth_SL // silverlight, does this matter?
{
public partial class MainPage : PhoneApplicationPage
{
DispatcherTimer Timer = new DispatcherTimer();
StreamSocket socket = new StreamSocket();
StreamWriter writer;
StreamReader reader;
public MainPage()
{
InitializeComponent();
Timer.Interval = TimeSpan.FromMilliseconds(1000); // dispatcher timer used to check for incoming data from arduino
Timer.Tick += Timer_Tick; // event handler for dispatcher timer
}
protected override void OnNavigatedFrom(NavigationEventArgs e) // frees up memory
{
socket.Dispose();
}
private void Connect_But_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
ConnectToBluetooth();
}
private async void ConnectToBluetooth() // sets up the connection // this works fine
{
// Configure PeerFinder to search for all paired devices.
PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
var pairedDevices = await PeerFinder.FindAllPeersAsync();
if (pairedDevices.Count == 0)
{
Debug_Block.Text = "No paired devices were found.";
}
else
{
Debug_Block.Text = "Found";
PeerInformation selectedDevice = pairedDevices[0]; // pick the first paired device
try // 'try' used in the case the socket has already been connected
{
await socket.ConnectAsync(selectedDevice.HostName, "1");
writer = new StreamWriter(socket.OutputStream.AsStreamForWrite());
writer.AutoFlush = true;
reader = new StreamReader(socket.InputStream.AsStreamForRead());
Debug_Block.Text = "Connected";
}
catch (Exception x)
{
Debug_Block.Text = x.ToString();
}
}
}
private void SendButton_Tap(object sender, System.Windows.Input.GestureEventArgs e) // this works perfectly
{
try { writer.WriteLine("a"); } // attempts to write the ascii 'a' to the arduino which turns on the on-board LED
catch { Debug_Block.Text = "Failed to write"; }
}
private void SendButton_Off_Tap(object sender, System.Windows.Input.GestureEventArgs e) // this works perfectly
{
try { writer.WriteLine("b"); } // attempts to write the ascii 'b' to the arduino which turns off the on-board LED
catch { Debug_Block.Text = "Failed to write"; }
}
private void ReadButtonToggle_Tap(object sender, System.Windows.Input.GestureEventArgs e) // toggles the timer on and off
{
if(Timer.IsEnabled == true)
{
Timer.Stop();
Debug_Block.Text = "Timer Stopped";
}
else
{
Timer.Start();
Debug_Block.Text = "Timer Started";
}
}
void Timer_Tick(object sender, EventArgs e) // THIS IS THE PROBLEM
{
Debug_Block.Text = "Tick";
Debug_Block.Text = reader.ReadLine(); // <-- ALWAYS FREEZES HERE
Timer.Stop(); // This line is temporary for debugging
}
}
}

WriteableBitmapExtension crashes app on device

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.
}
}
}

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.

WebException thrown when locking screen of the Emulator (WindowsPhone8)

I have a webrequest to get a xml.That works great but when i press F12(lock screen) while the the server is requested by my app...I got a WebException.
I use a taskCompeltionSource object...Here is my code
public async Task<String> Query(DataRequestParam dataRequestParam)
{
_dataRequestParam = dataRequestParam;
try
{
Result = "";
Result = await myDownloadString(dataRequestParam);
}
catch (WebException we)//ERROR IS CAUGHT HERE
{
throw new WebException(we.Message);
}
catch (Exception ex)
{
throw new MyException(ex.Message);
}
return Result;
}
public static Task<string> myDownloadString(DataRequestParam dataRequestParam)
{
var tcs = new TaskCompletionSource<string>();
var web = new WebClient();
if (!string.IsNullOrEmpty(dataRequestParam.AuthentificationLogin))
{
System.Net.NetworkCredential account = new NetworkCredential(dataRequestParam.AuthentificationLogin, dataRequestParam.AuthentificationPassword);
web.Credentials = account;
}
web.DownloadStringCompleted += (s, e) =>
{
if (e.Error != null) tcs.TrySetException(e.Error);
else if (e.Cancelled) tcs.TrySetCanceled();
else tcs.TrySetResult(e.Result);
};
web.DownloadStringAsync(dataRequestParam.TargetUri);
return tcs.Task;
}
If you haven't disabled ApplisationIdleDetection, your process is stopped while entering Lock screen - thus you probably get the exception - like I've said in comment. Disabling will solve this issue, but you must be aware of few things:
you will still get the exception when hitting Start Button (or other case putting your app to dormant state). In this case your app is stopped and there is no way to prevent this behaviour.
you must fulfill certification requirements when disabling App Idle Detection - point 6.3
if you want to download files in the Background (lock screen, after closing/leaving app) then you can think of Background Transfers

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);
}