CGContextDrawImage camera app crashes

Hello All,
My first post on this forum. I am trying to obtain an image using the AVCaptureSession. I followed this tutorial http://www.benjaminloulier.com/posts/2-ios4-and-direct-access-to-the-camera. I am creating uiimage from image ref and then obtaining pixels from that uiimage. But the app crashes after sometime (less than 30s). I tried analyzing using Leaks and that too crashes. Using logs I found the app crashes just before the line  CGContextDrawImage(context, rect, image1.CGImage); Do you guys have any suggestions on what I might be doing wrong. I also see Memory Allocation errors a few seconds before the app crashes. Please help.
Please find the code below:
// Create a UIImage from sample buffer data
- (UIImage *) imageFromSampleBufferCMSampleBufferRef) sampleBuffer
lock = @"YES";
CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
// Lock the base address of the pixel buffer
CVPixelBufferLockBaseAddress(imageBuffer, 0);
// Get the number of bytes per row for the pixel buffer
void *baseAddress = CVPixelBufferGetBaseAddress(imageBuffer);
// Get the number of bytes per row for the pixel buffer
size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
// Get the pixel buffer width and height
size_t width = CVPixelBufferGetWidth(imageBuffer);
size_t height = CVPixelBufferGetHeight(imageBuffer);
// Create a device-dependent RGB color space
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
size_t bufferSize = CVPixelBufferGetDataSize(imageBuffer);
// Create a Quartz direct-access data provider that uses data we supply.
NSData *data = [NSData dataWithBytes:baseAddress length:bufferSize];
CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data);
CGImageRef quartzImage = CGImageCreate(width, height, 8, 32, bytesPerRow,
              colorSpace, kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Little,
              dataProvider, NULL, true, kCGRenderingIntentDefault);
CGDataProviderRelease(dataProvider);
// Unlock the pixel buffer
CGColorSpaceRelease(colorSpace);
// Create an image object from the Quartz image
UIImage *image = [UIImage imageWithCGImage:quartzImage];
// Release the Quartz image
CGImageRelease(quartzImage);
CVPixelBufferUnlockBaseAddress(imageBuffer,0);
baseAddress = nil;
[data  release];
lock = @"NO";
return(image);
-(void)calculate
@try {
        UIImage *image1 = [self stillImage];   //Capture an image from the camera.
        //Extract the pixels from the camera image.
        CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
        size_t bytesPerRow = image1.size.width*4;
        unsigned char* bitmapData = (unsigned char*)malloc(bytesPerRow*image1.size.height);
        CGContextRef context = CGBitmapContextCreate(bitmapData, image1.size.width, image1.size.height, 8, bytesPerRow,colourSpace,kCGImageAlphaPremultipliedFirst|kCGBitmapByteOrder32Big);
        CGColorSpaceRelease(colourSpace);
        CGContextDrawImage(context, rect, image1.CGImage);
        unsigned char* pixels = (unsigned char*)CGBitmapContextGetData(context);
        totalLuminance = 0.0;
        for(int p=0; p<image1.size.width*image1.size.height*4; p+=4)
            totalLuminance += pixels[p]*0.3 + pixels[p+1]*0.59 + pixels[p+2]*0.11;
        totalLuminance /= (image1.size.height * image1.size.width);                  
        pixels = nil;
        bitmapData = nil;
        [image1 release];
    CGContextRelease(context);
        //image1 = nil;
        //totalLuminance = [n floatValue];                   //Calculate the total luminance.
        float f = [del.camcont.slider value];
        float total = totalLuminance * f;
        NSString *ns = [NSString stringWithFormat:@"Lux : %0.2f", total];
        NSLog(@"slider = %f",f);
        NSLog(@"totlaluminance = %f",totalLuminance);
        NSLog(@"%@",ns);
        //NSString *ns = [NSString initWithFormat:@"Lux : %0.2f", total];
        [del.camcont.lux setText:ns];//Display the total luminance.
        self.stillImage = nil;
        //[self.stillImage release];
         ns = nil;
        //n = nil;
        //del = nil;
    @catch (NSException *exception) {
        NSLog(@"main: Caught %@: %@", [exception name], [exception reason]);

The error happens in the Calculate method which uses the Image retrieved from the AVCaptureSession ImageBuffer to do some calculations. Calculate method is called every second directly from the function which gets the still image.
A few seconds later I get Memory Allocation Error at line:
for(int p=0; p<image1.size.width*image1.size.height*4; p+=4)
   totalLuminance += pixels[p]*0.3 + pixels[p+1]*0.59 + pixels[p+2]*0.11;
And then after a few iterations crashes at the line
CGContextDrawImage(context, rect, image1.CGImage);
Can someone please guide me on how I can make sure I am releasing the memory allocated to objects properly.
Thanks

Similar Messages

  • IPhone Camera App Crashed...

    Hello, I was taking some pictures with the iPhone camera app when all of the sudden after taking the picture, the camera app closed and the iPhone screen showed the shutdown spinwheel for a few seconds and then returning the the unlock screen. When I reopened the picture app, the picture that I took before the crash was gone. What could have cause this crash issue? but most importantly where's the picture? is it gone or was transmitted to somewhere else (folder, camera roll, iCloud, etc.)?
    Thanks for the assistance!
    P.S. I am looking at the iPhone logs and see that there was a springboard crash near the time of the crash. Can a springboard crash cause the iPhone to show a shutdown spinwheel and then leave you back in the log in screen?

    I am using iOS6.1.1
    Can you try to load up the apples and try take some HDR photos.

  • Photos and camera apps crash when I hit camera roll/take a picture

    After updating to ios5, I can no longer access my camera roll, not take a picture.  When I hit camera roll, photos crashes.  When I take a picture it says saving, then crashes.  I have tried turning off the apps and reopening them. I have tried restarting/resetting.  I have tried turning it off and letting it sit for 3 days. I tried accessing my camera roll through other apps like facebook, twitter, photoshop but it crashes. I tried to access my camera roll from iphoto and import my pictures but my iphone no longer comes up in iphoto.  I feel as though that restoring it may be the only option left, but I do not want to lose my photos and there's still no guarantee that photos and camera will work after restoring.  Anyone else ever hear of this before? Help!

    There is a similar thread elsewhere...but to save you the search, simply go to this page:
    http://www.iphoneincanada.ca/how-to/how-to-fix-iphone-camera-roll-crash-and-phot os-turned-to-other-in-itunes/
    The discussion in the other thread leads to that link...
    Simply put...I had the same problem, found that link, solved the problem!

  • Moto X Camera App Crashes When Taking Movies

    Recently, the camera app has started crashing whenever I try to take a movie with my Moto X.  Has anyone else been having this problem?

    I'm also having this problem AND a coworker is having the same issue.  I called motorola and they suggested starting in safe mode to determine if a 3rd party app was effecting the camera, but it crashed in safe mode too. 
    Anyone have an answer to this?

  • Why does Camera App crash?

    Recently the Camera App on my iPhone 4s started to crash irregularly - in particular, when I take a picture without unlocking the screen and when I then try to look at the picture (which used to work fine before). The screen simply freezes (with a blurry version of the picture visible) and the iPhone doesn't react to anything (including the "Home" button). If I do nothing, after a while it seems to go through an "Auto-reboot" - the white apple appears, and then it's back to normal. Can anyone comment on the cause and how to fix/avoid this?

    Hello Sebastian,
    Thank you for contacting Apple Support Communities.
    You can use the following article to troubleshoot your iPhone camera issues:
    iPhone: Hardware troubleshooting
    http://support.apple.com/kb/TS2802
    You will want to go to the Camera section.
    Regards,
    Jeff D.

  • Camera app crashing

    hello,
    i can't start my camera app anymore, actually not any app that makes use of the cam. they all just crash right after starting them. I'm running pr 1.3 since it first became availble, but today was the first time i noticed this problem. any suggestions how i might start about determining the cause of this?
    thanks, Ben

    delete the fcamera app and all the camera related apps u got from the app manager, than reboot, and the camera should work fine .
    Reality is wrong....dreams are for real... 2pac .
    don't forget to hit that green kudos

  • Camera App Crash since update to IOS 7.1.1

    Ever since I updated to IOS 7.1.1, i've noticed a strange behavior of the Camera app, on my iPhone  4S.
    If I enable the HDR function, I can take a picture, but it will only save the non-HDR and then it crashes.
    It's like it's having difficulties in saving the HDR photo.
    When it occurs, I get the feeling that it might be memory related (as if it doesn't have enough free memory available to process &amp; store the HDR photo).
    I have enough memory available and also enough storage space.
    This didn't occur before the 7.1.1 update.
    I've tried a reboot of the phone, clean re-install in iTunes (iTunes redownloads the ipsw file), afterwhich I restore from latest backup, but the problem remains.
    Anybody have any ideas, besides the ones i already tried?

    If you restore as a NEW device (not from a backup), does the same behavior occur?

  • Camera app crashes iPhone 4s after upgrading to 8.0 then downgrading to 7.1.2

    I have an iPhone 4s.  When ios 8 came out, I updgraded then realized over the next day that it slowed the phone down.  So I then reverted to 7.1.2.  After that, I have had a lot of trouble with the stock camera app.  It has locked up my phone many times and I have had to do a hard reset.  Does anyone have any ideas? 

    Apple was supporting the downgrade for a couple of days after ios 8 came out.  I downgraded with an Apple digitally signed version of 7.1.2 and I didn't hack anything. 

  • Windows Phone camera App crash when switching to another page

    I am creating a Simple Face Detection App for Windows Phone in C#. I turn on my camera , everything works perfect and FaceDetector works too, but when I try to navigate to other page my App always crashes and I do not why. I tried to test my App in Windows
    Phone Emulator and here the navigation works. I also tried debug my App in real device, but there the method OnNavigatedFrom is never hit.
    FaceDetection.xaml.cs
    public partial class FaceDetection : PhoneApplicationPage
    #region member variables
    const string MODEL_FILE = "models/haarcascade_frontalface_alt.xml";
    FaceDetector.Detector _detector;
    int _downsampleFactor = 2;
    private byte[] _pixelDataGray;
    private byte[] _pixelDataDownsampled;
    private int[] _pixelDataGrayInt;
    private WriteableBitmap _wb;
    private DateTime _lastUpdate;
    public static int pocet = 5;
    double point1;
    double point2;
    double heightRectangle;
    double widthRectangle;
    #endregion
    public FaceDetection()
    InitializeComponent();
    _detector = new FaceDetector.Detector(XDocument.Load(MODEL_FILE));
    private void NewCameraFrame(object sender, CameraFrameEventArgs cameraFrameEventArgs)
    PageOrientation orientaciaObrazovky = ((PhoneApplicationFrame)Application.Current.RootVisual).Orientation;
    cameraViewer.UpdateOrientation(orientaciaObrazovky);
    var w = cameraViewer.CameraWidth;
    var h = cameraViewer.CameraHeight;
    if (_pixelDataGray == null || _pixelDataGray.Length != h * w)
    _pixelDataGray = new byte[w / _downsampleFactor * h / _downsampleFactor];
    _pixelDataDownsampled =
    new byte[w / _downsampleFactor * h / _downsampleFactor];
    _pixelDataGrayInt = new int[w / _downsampleFactor * h / _downsampleFactor];
    _wb = new WriteableBitmap(w / _downsampleFactor, w / _downsampleFactor);
    _lastUpdate = DateTime.Now;
    Utils.DownSample(cameraFrameEventArgs.ARGBData, w, h, ref _pixelDataGrayInt, _downsampleFactor);
    Utils.ARGBToGreyScale(_pixelDataGrayInt, ref _pixelDataGray);
    Utils.HistogramEqualization(ref _pixelDataGray);
    Utils.GrayToARGB(_pixelDataGray, ref _pixelDataGrayInt);
    List<FaceDetector.Rectangle> faces = new List<FaceDetector.Rectangle>();
    if (orientaciaObrazovky == PageOrientation.PortraitUp || orientaciaObrazovky == PageOrientation.PortraitDown)
    int scalw = w / _downsampleFactor;
    int scalh = h / _downsampleFactor;
    int[] _pixelDataGrayIntRotated = new int[scalw * scalh];
    for (int x = 0; x < scalw; x++)
    for (int y = 0; y < scalh; y++)
    _pixelDataGrayIntRotated[y + x * scalh] = _pixelDataGrayInt[x + y * scalw];
    faces = _detector.getFaces(
    _pixelDataGrayIntRotated,
    h / _downsampleFactor,
    w / _downsampleFactor,
    2f, 1.25f, 0.1f, 1, false, false); // height-width swapped
    else
    faces = _detector.getFaces(
    _pixelDataGrayInt,
    w / _downsampleFactor,
    h / _downsampleFactor,
    2f, 1.25f, 0.1f, 1, false, false);
    var elapsed = (DateTime.Now - _lastUpdate).TotalMilliseconds;
    _pixelDataGrayInt.CopyTo(_wb.Pixels, 0);
    _wb.Invalidate();
    Dispatcher.BeginInvoke(delegate()
    cnvsFaceRegions.Children.Clear();
    foreach (var r in faces)
    System.Windows.Shapes.Rectangle toAdd = new System.Windows.Shapes.Rectangle();
    TranslateTransform loc = new TranslateTransform();
    if (orientaciaObrazovky == PageOrientation.PortraitUp)
    loc.X = r.X * _downsampleFactor / (double)w * cnvsFaceRegions.ActualWidth;
    loc.Y = r.Y * _downsampleFactor / (double)w * cnvsFaceRegions.ActualHeight;
    point1 = r.X;
    point2 = r.Y;
    else if (orientaciaObrazovky == PageOrientation.PortraitDown)
    loc.X = r.X * _downsampleFactor / (double)w * cnvsFaceRegions.ActualWidth;
    loc.Y = r.Y * _downsampleFactor / (double)w * cnvsFaceRegions.ActualHeight;
    point1 = r.X;
    point2 = r.Y;
    else if (orientaciaObrazovky == PageOrientation.LandscapeLeft)
    loc.X = r.X * _downsampleFactor / (double)w * cnvsFaceRegions.ActualWidth - 50;
    loc.Y = r.Y * _downsampleFactor / (double)w * cnvsFaceRegions.ActualHeight + 90;
    point1 = r.X;
    point2 = r.Y;
    else if (orientaciaObrazovky == PageOrientation.LandscapeRight)
    loc.X = r.X * _downsampleFactor / (double)w * cnvsFaceRegions.ActualWidth+50 ;
    loc.Y = r.Y * _downsampleFactor / (double)w * cnvsFaceRegions.ActualHeight -90;
    point1 = r.X;
    point2 = r.Y;
    toAdd.RenderTransform = loc;
    toAdd.Width = r.Width * _downsampleFactor + 50;
    toAdd.Height = r.Height * _downsampleFactor + 50;
    toAdd.Stroke = new SolidColorBrush(Colors.Red);
    cnvsFaceRegions.Children.Add(toAdd);
    widthRectangle = toAdd.Width;
    heightRectangle = toAdd.Height;
    point1 = (loc.X);
    point2 = (loc.Y);
    protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
    base.OnNavigatedTo(e);
    cameraViewer.SaveToCameraRoll = true;
    cameraViewer.NewCameraFrame += NewCameraFrame;
    cameraViewer.StartPumpingFrames();
    CameraButtons.ShutterKeyHalfPressed += OnButtonHalfPress;
    CameraButtons.ShutterKeyPressed += OnButtonFullPress;
    CameraButtons.ShutterKeyReleased += OnButtonRelease;
    protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
    base.OnNavigatedFrom(e);
    cameraViewer.StopPumpingFrames();
    CameraButtons.ShutterKeyHalfPressed -= OnButtonHalfPress;
    CameraButtons.ShutterKeyPressed -= OnButtonFullPress;
    CameraButtons.ShutterKeyReleased -= OnButtonRelease;
    private void OnButtonHalfPress(object sender, EventArgs e)
    cameraViewer.NewCameraFrame -= NewCameraFrame;
    private void OnButtonFullPress(object sender, EventArgs e)
    SaveScreenShots();
    private void OnButtonRelease(object sender, EventArgs e)
    cameraViewer.NewCameraFrame += NewCameraFrame;
    private static WriteableBitmap CropImage(WriteableBitmap source, int xOffset, int yOffset, int width, int height)
    var sourceWidth = source.PixelWidth;
    var result = new WriteableBitmap(width, height);
    for (var x = 0; x <= height - 1; x++)
    var sourceIndex = xOffset + (yOffset + x) * sourceWidth;
    var destinationIndex = x * width;
    Array.Copy(source.Pixels, sourceIndex, result.Pixels, destinationIndex, width);
    return result;
    private void SaveScreenShots()
    string namePerson = PhoneApplicationService.Current.State["TextBoxValue"] as String;
    bool b = cnvsFaceRegions.Children.Any();
    cnvsFaceRegions.Children.Clear();
    if (!b)
    MessageBox.Show("No face detected ");
    else
    for (int j = 1; j <= pocet; j++)
    using (var isoStore = IsolatedStorageFile.GetUserStoreForApplication())
    var bmp = new WriteableBitmap((int)this.ActualWidth, (int)this.ActualHeight);
    bmp.Render(this, null);
    byte[] bb = EncodeToJpeg(bmp);
    bmp.Invalidate();
    WriteableBitmap bmp2 = CropImage(bmp, (int)point1, (int)point2, (int)widthRectangle, (int)heightRectangle);
    using (var isoFileStream = isoStore.CreateFile(namePerson + j))
    System.Windows.Media.Imaging.Extensions.SaveJpeg(bmp2, isoFileStream, bmp.PixelWidth, bmp.PixelHeight, 0, 100);
    isoFileStream.Close();
    MessageBox.Show("Saved successfully " + pocet + " images");
    cameraViewer.NewCameraFrame += NewCameraFrame;
    public byte[] EncodeToJpeg(WriteableBitmap wb)
    using (MemoryStream stream = new MemoryStream())
    wb.SaveJpeg(
    stream,
    wb.PixelWidth,
    wb.PixelHeight,
    0,
    85);
    return stream.ToArray();
    private void cameraViewer_MouseLeftButtonDown_1(object sender, MouseButtonEventArgs e)
    cameraViewer.NewCameraFrame -= NewCameraFrame;
    private void cameraViewer_MouseLeftButtonUp_1(object sender, MouseButtonEventArgs e)
    SaveScreenShots();
    private void ApplicationBarMenuItem_Click(object sender, EventArgs e)
    NavigationService.Navigate(new Uri("/PersonAndGallery;component/Gallery.xaml", UriKind.Relative));
    CameraViewer.cs
    public class CameraFrameEventArgs : RoutedEventArgs
    public int[] ARGBData { get; set; }
    public static class AppGlobal
    public static bool isPortrait = true;
    public class CameraViewer : Grid
    #region Events
    public EventHandler<CameraFrameEventArgs> NewCameraFrame { get; set; }
    public EventHandler<ContentReadyEventArgs> NewCameraCaptureImage { get; set; }
    public EventHandler<CameraOperationCompletedEventArgs> CamInitialized { get; set; }
    #endregion
    #region Properties
    public int CameraWidth
    get { return _cameraWidth; }
    set { _cameraWidth = value; }
    public int CameraHeight
    get { return _cameraHeight; }
    set { _cameraHeight = value; }
    public bool PhotoOnPress
    get { return _photoOnPress; }
    set
    _photoOnPress = value;
    // CameraButtons.ShutterKeyPressed -= CameraButtonsOnShutterKeyPressed;
    if (_photoOnPress)
    // CameraButtons.ShutterKeyPressed += CameraButtonsOnShutterKeyPressed;
    public bool SaveToCameraRoll { get; set; }
    public PhotoCamera Camera
    get { return _camera; }
    public bool TakingPhoto
    get { return _takingPhoto; }
    #endregion
    #region Member Variables
    private PhotoCamera _camera; // the windows phone camera that takes the photos
    private int _cameraWidth = -1;
    private int _cameraHeight = -1;
    private Thread _pumpFramesThread;
    private static ManualResetEvent _pauseFramesEvent = new ManualResetEvent(true);
    private bool _takingPhoto;
    VideoBrush viewfinderBrush;
    private bool _photoOnPress;
    private SoundEffect _cameraShutterSound;
    private static ManualResetEvent _cameraCaptureEvent = new ManualResetEvent(true);
    private static ManualResetEvent _cameraInitializedEvent = new ManualResetEvent(false);
    private bool _pumpFrames;
    #endregion
    #region Constructor
    public CameraViewer()
    Unloaded += new RoutedEventHandler(OnUnloaded);
    PhotoOnPress = true;
    public override void OnApplyTemplate()
    base.OnApplyTemplate();
    #endregion
    #region Public methods
    public void StartPumpingFrames()
    _pauseFramesEvent = new ManualResetEvent(true);
    _cameraCaptureEvent = new ManualResetEvent(true);
    _cameraInitializedEvent = new ManualResetEvent(false);
    InitializeCamera();
    _pumpFrames = true;
    if (_pumpFramesThread == null)
    _pumpFramesThread = new Thread(PumpFrames);
    if (!_pumpFramesThread.IsAlive)
    _pumpFramesThread.Start();
    public void StopPumpingFrames()
    _pumpFrames = false;
    _pumpFramesThread = null;
    Camera.Dispose();
    public void TakePhoto()
    if (TakingPhoto)
    return;
    _cameraCaptureEvent.Reset();
    FrameworkDispatcher.Update();
    _cameraShutterSound.Play();
    _takingPhoto = true;
    Camera.CaptureImage();
    #endregion
    private void CameraButtonsOnShutterKeyPressed(object sender, EventArgs eventArgs)
    if (_photoOnPress && !TakingPhoto)
    _cameraCaptureEvent.WaitOne();
    TakePhoto();
    private void OnUnloaded(object sender, RoutedEventArgs e)
    _cameraInitializedEvent.Reset();
    public void InitializeCamera()
    _cameraInitializedEvent.Reset();
    // Check to see if the camera is available on the device.
    if ((PhotoCamera.IsCameraTypeSupported(CameraType.Primary) == true) ||
    (PhotoCamera.IsCameraTypeSupported(CameraType.FrontFacing) == true))
    // Initialize the default camera.
    _camera = new Microsoft.Devices.PhotoCamera();
    //Event is fired when the PhotoCamera object has been initialized
    Camera.Initialized +=
    new EventHandler<Microsoft.Devices.CameraOperationCompletedEventArgs>(CameraInitialized);
    Camera.CaptureImageAvailable += CameraOnCaptureImageAvailable;
    Camera.CaptureCompleted += CameraOnCaptureCompleted;
    //Set the VideoBrush source to the camera
    // var viewfinderBrush = new VideoBrush();
    viewfinderBrush = new VideoBrush();
    viewfinderBrush.Stretch = Stretch.Fill;
    viewfinderBrush.RelativeTransform = new CompositeTransform { CenterX = 0.5, CenterY = 0.5 };
    viewfinderBrush.SetSource(Camera);
    System.Windows.Shapes.Rectangle rect = new System.Windows.Shapes.Rectangle();
    rect.Fill = viewfinderBrush;
    this.Children.Add(rect);
    Stream stream = TitleContainer.OpenStream("models/shutter.wav");
    _cameraShutterSound = SoundEffect.FromStream(stream);
    // CameraButtons.ShutterKeyPressed -= CameraButtonsOnShutterKeyPressed;
    if (_photoOnPress)
    // CameraButtons.ShutterKeyPressed += CameraButtonsOnShutterKeyPressed;
    else
    // The camera is not supported on the device.
    MessageBox.Show(
    "Sorry, this sample requires a phone camera and no camera is detected. This application will not show any camera output.");
    private void CameraOnCaptureCompleted(object sender, CameraOperationCompletedEventArgs cameraOperationCompletedEventArgs)
    _cameraCaptureEvent.Set();
    _takingPhoto = false;
    private void CameraOnCaptureImageAvailable(object sender, ContentReadyEventArgs contentReadyEventArgs)
    if (SaveToCameraRoll)
    Dispatcher.BeginInvoke(() =>
    WriteableBitmap bitmap =
    CreateWriteableBitmap(contentReadyEventArgs.ImageStream,
    (int)Camera.Resolution.Width,
    (int)Camera.Resolution.Height);
    // SaveCapturedImage(bitmap);
    //TakeScreenShots();
    if (NewCameraCaptureImage != null)
    NewCameraCaptureImage.Invoke(this, contentReadyEventArgs);
    // Helper for CameraOnCaptureImageAvailable
    private void SaveCapturedImage(WriteableBitmap imageToSave)
    var stream = new MemoryStream();
    imageToSave.SaveJpeg(stream, imageToSave.PixelWidth, imageToSave.PixelHeight, 0, 100);
    //Take the stream back to its beginning because it will be read again
    //when saving to the library
    stream.Position = 0;
    var library = new MediaLibrary();
    string fileName = string.Format("{0:yyyy-MM-dd-HH-mm-ss}.jpg", DateTime.Now);
    library.SavePictureToCameraRoll(fileName, stream);
    //save to Save Photo
    Picture pic;
    private void TakeScreenShots()
    WriteableBitmap bmp = new WriteableBitmap((int)this.ActualWidth, (int)this.ActualHeight);
    bmp.Render(this, null);
    byte[] bb = EncodeToJpeg(bmp);
    bmp.Invalidate();
    MemoryStream mem = new MemoryStream();
    bmp.SaveJpeg(mem, bmp.PixelWidth, bmp.PixelHeight, 0, 100);
    mem.Seek(0, System.IO.SeekOrigin.Begin);
    if (mem != null)
    MediaLibrary library = new MediaLibrary();
    try
    pic = library.SavePicture("Mask_" + Guid.NewGuid().ToString(), mem);
    MessageBox.Show("Your picture is now accessible through the Saved Picture album.", "Saved successfully.", MessageBoxButton.OK);
    catch (Exception ex)
    MessageBox.Show("Unable to save the photo." + ex);
    public byte[] EncodeToJpeg(WriteableBitmap wb)
    using (MemoryStream stream = new MemoryStream())
    wb.SaveJpeg(
    stream,
    wb.PixelWidth,
    wb.PixelHeight,
    0,
    85);
    return stream.ToArray();
    // Creates a WriteableBitmap from an imageStream
    private WriteableBitmap CreateWriteableBitmap(Stream imageStream, int width, int height)
    var bitmap = new WriteableBitmap(width, height);
    imageStream.Position = 0;
    bitmap.LoadJpeg(imageStream);
    return bitmap;
    private void CameraInitialized(object sender, CameraOperationCompletedEventArgs e)
    if (e.Succeeded)
    try
    // available resolutions are ordered based on number of pixels in each resolution
    CameraWidth = (int)Camera.PreviewResolution.Width;
    CameraHeight = (int)Camera.PreviewResolution.Height;
    if (CamInitialized != null)
    CamInitialized.Invoke(this, e);
    _cameraInitializedEvent.Set();
    _pauseFramesEvent.Set();
    catch (ObjectDisposedException)
    // If the camera was disposed, try initializing again
    private void PumpFrames()
    _cameraInitializedEvent.WaitOne();
    int[] pixels = new int[CameraWidth * CameraHeight];
    int numExceptions = 0;
    while (_pumpFrames)
    _pauseFramesEvent.WaitOne();
    _cameraCaptureEvent.WaitOne();
    _cameraInitializedEvent.WaitOne();
    try
    Camera.GetPreviewBufferArgb32(pixels);
    catch (Exception e)
    // If we get an exception try capturing again, do this up to 10 times
    if (numExceptions >= 10)
    throw e;
    numExceptions++;
    continue;
    numExceptions = 0;
    _pauseFramesEvent.Reset();
    Deployment.Current.Dispatcher.BeginInvoke(
    () =>
    if (NewCameraFrame != null && _pumpFrames)
    NewCameraFrame(this, new CameraFrameEventArgs { ARGBData = pixels });
    _pauseFramesEvent.Set();
    //na zmenu orientacie
    public void UpdateOrientation(PageOrientation orientation)
    if (orientation == PageOrientation.PortraitDown)
    viewfinderBrush.RelativeTransform =
    new CompositeTransform { CenterX = 0.5, CenterY = 0.5, Rotation = 270 };
    /* else if (orientation == PageOrientation.PortraitDown && cameraType == 2)
    viewfinderBrush.RelativeTransform =
    new CompositeTransform { CenterX = 0.5, CenterY = 0.5, Rotation = 90 };
    else if (orientation == PageOrientation.PortraitUp && cameraType == 2)
    viewfinderBrush.RelativeTransform =
    new CompositeTransform { CenterX = 0.5, CenterY = 0.5, Rotation = -90 };
    else if (orientation == PageOrientation.PortraitUp)
    viewfinderBrush.RelativeTransform =
    new CompositeTransform { CenterX = 0.5, CenterY = 0.5, Rotation =90 };
    else if (orientation == PageOrientation.LandscapeLeft)
    viewfinderBrush.RelativeTransform =
    new CompositeTransform { CenterX = 0.5, CenterY = 0.5, Rotation = 0 };
    else if (orientation == PageOrientation.LandscapeRight)
    viewfinderBrush.RelativeTransform =
    new CompositeTransform { CenterX = 0.5, CenterY = 0.5, Rotation = -180 };
    Thanks for reply.

    Hi Facko,
    Thanks for posting at the forum, however it could be really difficult for us to copy/paste your code and try to repro the issue, I would suggest you to provide a repro sample for us so that we can debug for you.
    And base on your description, looks like your app only crashes on the real device, but not on the emulator. I have question here, how the app works on the emulator?
    As I know if we open the camera on emulator, the only thing we can see is kind of small color blocks instead of the real images.
    You could also try to close the camera and then dispose the object to see if it works.
    --James
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Why does my camera app crash after i update my iphone 5S to IOS 7.0.6?

    and i updated it to IOS 7.1 hoping it will help, but it failed again.

    Try This...
    Close All Open Apps... Sign Out of your Account... Perform a Reset... Try again...
    Reset  ( No Data will be Lost )
    Press and Hold the Sleep/Wake Button and the Home Button at the Same Time...
    Wait for the Apple logo to Appear...
    Usually takes about 15 - 20 Seconds... ( But can take Longer...)
    Release the Buttons..
    If no joy... Try a Restore... First from Backup... Then as New if necessary.
    Make sure you have the Latest Version of iTunes (v11.1.5) Installed on your computer
    iTunes free download from www.itunes.com/download
    If the issue persists... Then a Visit to an Apple Store or AASP (Authorized Apple Service Provider) is the Next Step... Be sure to make an appointment first...

  • Nokia Camera App Crash

    Hi
    I am using a Lumia 1020 with cyan update. Sometimes while opening video recording its geting crashed and the phone got hanged. I need to soft reset to bring it back. Is anybody facing this issue. Is this a software bug or hardware issue.plese help me.

    How about resetting the phone, SoorajV? Go to Settings > about > reset your phone. As this process will delete all your personal data, we recommend creating a backup file: Back up my stuff. If you've already done this, you can proceed with using the Nokia Software Recovery Tool: https://expertcentre.nokia.com/en/articles/kbarticles/Pages/Nokia-Software-Recovery-Tool.aspx.
    Let us know the outcome.

  • Can't access photos in camera roll - camera and  photo app crashes

    Have iphone 4 with iOS 5.0. Took pictures but now I can't access any photo in the Camera Roll. When I now try to take a picture, Camera app crashes. If I try to access the Camera Roll via Photo App, it too crashes. Can't see the photos from iTunes either. Shows it as unknown data. Is there anyway to rebuild the photo library or remove a corrupted photo since I think that is the problem. Any help would be appreciated.

    Thanks to Steve Kehlet who posted the solution that helped me and saved my day, https://discussions.apple.com/message/16405821#16405821
    Follow the link:
    http://www.iphoneincanada.ca/how-to/how-to-fix-iphone-camera-roll-crash-and-phot os-turned-to-other-in-itunes/
    You will need to download PhoneView, but the free 7 day demo does the job - and my camera and photo app are up and running again!

  • Camera app killing battery iphone 4s ios8.1.1

    *as discussions.apple.com does not let me reply to existing topics I had to start a new one - typical of the modern Apple!
    Since the update to ios8.1.1. every time I start my camera and take a picture with HDR or take a video my phone shuts down as it think the battery went dead. Never happened before ios8.1, only happens using the Camera app since update to ios8.1.1. It's made my iphone completely useless for quick photography through the slide up function now. Open Camera, take picture, BANG, need to recharge. From 91% to claiming it is empty is the record. I can listen to music on the same phone for over 6 hours, yet it thinks the battery is dead when I take a picture? Once popped into the electricity it will always show black screen with empty battery with just the red bit left... after a few seconds the phone starts up and it will always show over 50% battery!
    I know there are more photography apps out there, but surely the basic Camera app that can be accessed quickly through the locked screen should not be so poorly done it makes the phone think my battery is empty???

    Accepted, in 8.1 i not seen any problem (except terrible performance) but after update on 8.1.1 my iphone 4s starts shutdown to often, not only camera-app crash it, for example after playing music it shutdowns, after send watsapp message it shutdowns. if i try turn on iphone immediatly after shutdown it show me discharged battery, but worth the wait approximately 30min and it starts as it was in 30-40% of battery.
    plz apple, if u cant normally support 4s get me chance downgrade it to ios6

  • IPhone 5s camera app won't open and crashes from lock screen and control menu

    Hello, I recntly got a Black iPhone 5s 16gb and it was working fine. Then sudenly the camera app started crashing after i took photos. Soon later the camera app wont open at all and if i try opening from the lockscreen the phone just reboots. Ive tried just resetting all settings just off the phone and nothing happened, so i decided to restore my iPhone to factory settings and still had no luck. I also had a problem with the flashlight it stopped working aswell (went gray on control menu) and all flashlight apps wont even. I also found out that my snapcat front camera (selfie camera works) and there is no 'swap button.
    This is the second time Ive been suffering from a camera issue the first one was ery similar the shutter wouldnt open because there was no memory, but now ive got 9.1GB free so this cant be the problem.  Other reviews i have read state that the phone has a hardwear issue and need to be replaced.

    FIX FOR REAR CAMERA AND FLASHLIGHT!!!
    I also had the same flash and rear camera problems as everyone else but I figured it was a software problem.
    To fix the flash/flashlight, simply download the flashlight app. The one everyone used before iOS 7. The flash should work immediately.
    To fix the rear camera go to Settings > General > Restrictions. Enable restrictions and turn the Camera off, then take the restriction off. Check your camera, it should work immediately.
    Hope this answers a lot of questions and saves a bunch of money due to Apple's failures.
    Cheers,
    Tim

  • Camera API problem after app crashed (winrt)

    Dear Sirs.
    I am developing windows phone runtime app (8.1) and testing it on my Nokia Limia 520 smartphone.
    I work with Camera Api (CameraPreviewImageSource from Nokia.Graphics.Imaging (Nokia Imaging SDK v 1.2.151 from NuGet)). But I think this package is not important info.
    Sometimes, after using camera api many times, for instance more than 30th the app crahes. The reason of app crash in my view not important too. (Of course it is important but I ask about restore phone state after the app crashes because it may happens after
    the memory consumption exception for example)
    I think because app crahes I don't call Dispose method for Camera Api and after I restart the app I see the green screen in the view where I use camera api to show user images from the camera. Also I see the green screen when I launch the standart app for capturing
    photo.
    It will fix only when I restart the phone.
    I have tried to do the following things:
    1) Add handler for OnSuspending event:
      private async void OnSuspending(object sender, SuspendingEventArgs e)
                var deferral = e.SuspendingOperation.GetDeferral();
                //cleanup camera resources
                await CleanupCaptureResourcesAsync();
                deferral.Complete();
    2) Add handler for OnUnhandledException event:
    private void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
            e.Handled = true;
            CleanupCaptureResourcesAsync().GetAwaiter().GetResult();
            Frame rootFrame = Window.Current.Content as Frame;
            if (rootFrame!=null) rootFrame.Navigate(typeof (BlankPage11), null);
    CleanupCaptureResourcesAsync method:
     public async Task CleanupCaptureResourcesAsync()
                if (CameraPreviewImageSource != null)
                    CameraInitialized = false;
                    await CameraPreviewImageSource.StopPreviewAsync();
                    CameraPreviewImageSource.Dispose();
                    CameraPreviewImageSource = null;
    It is works when I relaunch the app (manualy close and start it again). But when exception occurs it is not works.
    Could you please help me? How can I handle an exception, or if it not possible in some ways (as I have read at https://msdn.microsoft.com/en-us/library/dn532194.aspx) is there any way to restore Camera Api after app launched again (after crash)?
    Best regards,
    Aleksandr Terentev

    Thank you for your answer.
    However, I think the WinDebug wouldn’t help me enough. Because apps may crash in many situations. In my view I need either app global exception mechanism for the purpose of releasing camera api by calling Dispose method when an exception
    occurs or mechanism for restoring the state of the phone camera api after app has crashed.
    Yes, I can save the realtime app status but it wouldn’t help. Because when you try to initialize camera api again it wouldn’t work because the app didn’t call Dispose method and didn’t release the phone camera api.
    This situation is described in the MSDN article:
     “It is extremely important that you properly shut down and dispose of the MediaCapture object and related objects when your app is suspended. Failure to do so could interfere with other apps accessing the device's camera which will
    result in a negative user experience for your app.”  
    (https://msdn.microsoft.com/en-us/library/windows/apps/xaml/dn642092.aspx)
    But when the app crashes, OnSuspending event won’t be triggered, in my view. Therefore, after this no one app can use the camera and you have to restart your phone.

Maybe you are looking for

  • Testing Automation

    hi guys, Do you use any tools to handle your coldfusion application testing? if yes, what do you use? I'm trying to find something that i can for testing that will not involve the developer team

  • Uploading flash website problem

    I made a website in flash and everything is working fine in the files. When I tested the site on my computer everything was working just the way it should. However when I finally uploaded it to my server not everything worked. I had 3 galleries that

  • Changing all photos in event to SAME date

    I have many photos in an event that have a variety of dates.  I would like to change all photos to the SAME date.  All I can figure out to do is change the first photo, but then all of the other photos are time-shifted and still have different dates.

  • File size deviation between Finder and Quicktime

    Today I encountered a weird phenomenon: Some Quicktime .movs show different filesizes in the finder (e.g. 69,3MB) than the same clip has in Quicktime (Command-I says 34,71MB) This happens if the clip was opened, truncated and saved (under the same na

  • Define rules of variant

    hi   can any body explain me about day type variant.and let me know how to write variant rule for a day 4 hrs working if next day  is holiday and it is Saturday.please explain me these variant which is in below RULE     NO.     HOL.CLASS     HOL CLAS