/// <summary>
        /// Clicking on the save button saves the photo in DataContext.ImageStream to media library
        /// camera roll. Once image has been saved, the application will navigate back to the main page.
        /// </summary>
        private void saveButton_Click(object sender, EventArgs e)
        {
            try
            {
                // Reposition ImageStream to beginning, because it has been read already in the OnNavigatedTo method.
                _dataContext.ImageStream.Position = 0;

                MediaLibrary library = new MediaLibrary();
                library.SavePictureToCameraRoll("CameraExplorer_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".jpg", _dataContext.ImageStream);
                
                // There should be no temporary file left behind
                using (var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    var files = isolatedStorage.GetFileNames("CameraExplorer_*.jpg");
                    foreach (string file in files)
                    {
                        isolatedStorage.DeleteFile(file);
                        //System.Diagnostics.Debug.WriteLine("Temp file deleted: " + file);
                    }
                }

            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Saving picture to camera roll failed: " + ex.HResult.ToString("x8") + " - " + ex.Message);
            }

            NavigationService.GoBack();
        }
        private void SaveButton_Click(object sender, EventArgs e)
        {
            WriteableBitmap wb = new WriteableBitmap(mapControl, null);
            wb.Render(mapControl, null);
            MemoryStream memoryStream = new MemoryStream();
            wb.SaveJpeg(memoryStream, wb.PixelWidth, wb.PixelHeight, 0, 80);

            MediaLibrary library = new MediaLibrary();
            library.SavePictureToCameraRoll("SavedMap_" + DateTime.Now.ToString() + ".jpg", memoryStream.GetBuffer());
        }
 /// <summary>
 /// Saves the WriteableBitmap encoded as JPEG to the Media library.
 /// </summary>
 /// <param name="bitmap">The WriteableBitmap to save.</param>
 /// <param name="name">The name of the destination file.</param>
 /// <param name="quality">The quality for JPEG encoding has to be in the range 0-100, 
 /// where 100 is the best quality with the largest size.</param>
 /// <param name="saveToCameraRoll">If true the bitmap will be saved to the camera roll, otherwise it will be written to the default saved album.</param>
 public static Picture SaveToMediaLibrary(this WriteableBitmap bitmap, string name, int quality, bool saveToCameraRoll = false)
 {
    using (var stream = new MemoryStream())
    {
       // Save the picture to the WP media library
       bitmap.SaveJpeg(stream, bitmap.PixelWidth, bitmap.PixelHeight, 0, quality);
       stream.Seek(0, SeekOrigin.Begin);
       var mediaLibrary = new MediaLibrary();
       return saveToCameraRoll ? mediaLibrary.SavePictureToCameraRoll(name, stream) : mediaLibrary.SavePicture(name, stream);
    }
 }
 private async void Save_Clicked(object sender, RoutedEventArgs e)
 {
     using (MemoryStream stream = new MemoryStream())
     {
         WriteableBitmap bitmap = new WriteableBitmap(3552, 2448);
         await session.RenderToWriteableBitmapAsync(bitmap);
         bitmap.SaveJpeg(stream, bitmap.PixelWidth, bitmap.PixelHeight, 0, 100);
         stream.Seek(0, SeekOrigin.Begin);
         using (MediaLibrary mediaLibrary = new MediaLibrary())
             mediaLibrary.SavePictureToCameraRoll("Picture.jpg", stream);
         MessageBox.Show("Image saved!");
     }
 }
        private void share(object sender, RoutedEventArgs e)
        {
            //Create a filename for the JPEG file in isolated storage
            String tempJPEG = "TempJPEG";

            // Create a virtual store and file stream. Check for duplicate tempJPEG files.
            var myStore = IsolatedStorageFile.GetUserStoreForApplication();
            if (myStore.FileExists(tempJPEG))
            {
                myStore.DeleteFile(tempJPEG);
            }

            IsolatedStorageFileStream myFileStream = myStore.CreateFile(tempJPEG);

            // Create a stream out of the sample JPEG file.
            // For [Application Name] in the URI, use the project name that you entered
            // in the previous steps. Also, TestImage.jpg is an example;
            // you must enter your JPEG file name if it is different.
            StreamResourceInfo sri = null;
            Uri uri = new Uri("[Application Name];component/TestImage.jpg", UriKind.Relative);
            sri = Application.GetResourceStream(uri);

            // Create a new WriteableBitmap object and set it to the JPEG stream.
            BitmapImage bitmap = new BitmapImage();
            bitmap.CreateOptions = BitmapCreateOptions.None;
            bitmap.SetSource(sri.Stream);
            WriteableBitmap wb = new WriteableBitmap(bitmap);

            // Encode the WriteableBitmap object to a JPEG stream.
            wb.SaveJpeg(myFileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
            myFileStream.Close();

            // Create a new stream from isolated storage, and save the JPEG file to the media library on Windows Phone.
            myFileStream = myStore.OpenFile(tempJPEG, FileMode.Open, FileAccess.Read);

            // Save the image to the camera roll or saved pictures album.
            MediaLibrary library = new MediaLibrary();

                // Save the image to the camera roll album.
                Picture pic = library.SavePictureToCameraRoll("SavedPicture.jpg", myFileStream);
                MessageBox.Show("Image saved to camera roll album");
            /*    // Save the image to the saved pictures album.
                Picture pic = library.SavePicture("SavedPicture.jpg", myFileStream);
                MessageBox.Show("Image saved to saved pictures album");
            */

            myFileStream.Close();
        }
Exemple #6
0
    private async void Button_Click_2(object sender, RoutedEventArgs e) {
      CameraCaptureSequence cameraCaptureSequence = _cam.CreateCaptureSequence(1);

      MemoryStream stream = new MemoryStream();
      cameraCaptureSequence.Frames[0].CaptureStream = stream.AsOutputStream();

      await _cam.PrepareCaptureSequenceAsync(cameraCaptureSequence);
      await cameraCaptureSequence.StartCaptureAsync();

      stream.Seek(0, SeekOrigin.Begin);

      var library = new MediaLibrary();
      library.SavePictureToCameraRoll("pic1.jpg", stream);


    }
        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            CameraCaptureSequence seq;
            seq = captureDevice.CreateCaptureSequence(1);

            seq.Frames[0].DesiredProperties[KnownCameraPhotoProperties.SceneMode] = CameraSceneMode.Portrait;

            MemoryStream captureStream1 = new MemoryStream();

            seq.Frames[0].CaptureStream = captureStream1.AsOutputStream();
            await captureDevice.PrepareCaptureSequenceAsync(seq);

            await seq.StartCaptureAsync();
            captureStream1.Seek(0, SeekOrigin.Begin);
            MediaLibrary mediaLibrary = new MediaLibrary();
            mediaLibrary.SavePictureToCameraRoll( "1111.jpg", captureStream1);
 
        }
        private async void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            using (MemoryStream stream = new MemoryStream())
            using (var camera = await PhotoCaptureDevice.OpenAsync(CameraSensorLocation.Back,
                    PhotoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Back).First()))
            {
                var sequence = camera.CreateCaptureSequence(1);
                sequence.Frames[0].CaptureStream = stream.AsOutputStream();
                camera.PrepareCaptureSequenceAsync(sequence);
                await sequence.StartCaptureAsync();

                stream.Seek(0, SeekOrigin.Begin);

                using (var library = new MediaLibrary())
                {
                    library.SavePictureToCameraRoll("currentImage.jpg", stream);

                    BitmapImage licoriceImage = new BitmapImage(new Uri("currentImage.jpg", UriKind.Relative));
                    imgPlace.Source = licoriceImage;
                }
            }
        }
        /// <summary>
        /// Clicking on the save button saves the photo in MainPage.ImageStream
        /// to media library camera roll. Once image has been saved, the
        /// application will navigate back to the main page.
        /// </summary>
        private async void SaveButton_Click(object sender, EventArgs e)
        {
            _progressIndicator.Text = AppResources.SavingText;
            _progressIndicator.IsVisible = true;
            SystemTray.SetProgressIndicator(this, _progressIndicator);
            int selectedIndex = FilterPreviewPivot.SelectedIndex;

            DataContext dataContext = FilterEffects.DataContext.Instance;

            try
            {
                if (selectedIndex == 0)
                {
                    using (MediaLibrary library = new MediaLibrary())
                    {
                        library.SavePictureToCameraRoll(FileNamePrefix
                            + DateTime.Now.ToString() + ".jpg",
                            dataContext.FullResolutionStream);
                    }
                }
                else
                {
                    AbstractFilter filter = _filters[selectedIndex];

                    IBuffer buffer = await filter.RenderJpegAsync(
                        dataContext.FullResolutionStream.GetWindowsRuntimeBuffer());

                    using (MediaLibrary library = new MediaLibrary())
                    {
                        library.SavePictureToCameraRoll(FileNamePrefix
                            + DateTime.Now.ToString() + ".jpg", buffer.AsStream());
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to save the image: " + ex.ToString());
            }

            _progressIndicator.IsVisible = false;
            SystemTray.SetProgressIndicator(this, _progressIndicator);


            AdRequest adRequest = new AdRequest();
            adRequest.ForceTesting = true;
            interstitialAd.LoadAd(adRequest);
            interstitialAd.ReceivedAd += OnAdReceived;

            if (p == true)
            {


                p = false;

                q = true;

                interstitialAd.ShowAd();
                //NavigationService.Navigate(new Uri("/PreveiwPage.xaml", UriKind.Relative));

            }

            NavigationService.Navigate(new Uri("/Page1.xaml", UriKind.Relative));

            NavigationService.GoBack();
        }
        /// <summary>
        /// Clicking on the save button saves the photo in MainPage.ImageStream
        /// to media library camera roll. Once image has been saved, the
        /// application will navigate back to the main page.
        /// </summary>
        private async void SaveButton_Click(object sender, EventArgs e)
        {
            _progressIndicator.Text = AppResources.SavingText;
            _progressIndicator.IsVisible = true;
            SystemTray.SetProgressIndicator(this, _progressIndicator);
            int selectedIndex = FilterPreviewPivot.SelectedIndex;

            DataContext dataContext = FilterEffects.DataContext.Singleton;

            try
            {
                if (selectedIndex == 0)
                {
                    using (MediaLibrary library = new MediaLibrary())
                    {
                        library.SavePictureToCameraRoll(FileNamePrefix
                            + DateTime.Now.ToString() + ".jpg",
                            dataContext.ImageStream);
                    }
                }
                else
                {
                    AbstractFilter filter = _filters[selectedIndex];

                    IBuffer buffer = await filter.RenderJpegAsync(
                        dataContext.ImageStream.GetWindowsRuntimeBuffer());

                    using (MediaLibrary library = new MediaLibrary())
                    {
                        library.SavePictureToCameraRoll(FileNamePrefix
                            + DateTime.Now.ToString() + ".jpg", buffer.AsStream());
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to save the image: " + ex.ToString());
            }

            _progressIndicator.IsVisible = false;
            SystemTray.SetProgressIndicator(this, _progressIndicator);

            NavigationService.GoBack();
        }
Exemple #11
0
        public void SaveToIsolatedStorage(Stream imageStream, string fileName)
        {
            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (myIsolatedStorage.FileExists(fileName))
                {
                    myIsolatedStorage.DeleteFile(fileName);
                }

                IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(fileName);
                BitmapImage bitmap = new BitmapImage();
                bitmap.SetSource(imageStream);

                WriteableBitmap wb = new WriteableBitmap(bitmap);
                Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 100);
                fileStream.Close();
            }

            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                {
                    MediaLibrary mediaLibrary = new MediaLibrary();
                    Picture picture = mediaLibrary.SavePictureToCameraRoll(fileName, fileStream);

                    fileStream.Close();
                }
            }
        }
        private async Task<string> SaveToCameraRoll(Stream cameraImage, string filenameBase)
        {
            string filename = filenameBase + ".jpg";
            StorageFolder storageFolder = KnownFolders.CameraRoll;
            AutoResizeConfiguration resizeConfiguration = null;
            var buffer = StreamToBuffer(cameraImage);

            // Store low resolution image
            using (var source = new BufferImageSource(buffer))
            {
                var info = await source.GetInfoAsync();

                if (info.ImageSize.Width * info.ImageSize.Height > LibraryMaxArea)
                {
                    var compactedSize = CalculateSize(info.ImageSize, LibraryMaxSize, LibraryMaxArea);
                    resizeConfiguration = new AutoResizeConfiguration(LibraryMaxBytes, compactedSize,
                        new Size(0, 0), AutoResizeMode.Automatic, 0, ColorSpace.Yuv420);
                    buffer = await Nokia.Graphics.Imaging.JpegTools.AutoResizeAsync(buffer, resizeConfiguration);
                }

                using (var library = new MediaLibrary())
                {
                    library.SavePictureToCameraRoll(filename, buffer.AsStream());
                }
            }

            // Store high resolution image
            if (resizeConfiguration != null)
            {
                filename = filenameBase + HIGH_RESOLUTION_PHOTO_SUFFIX + @".jpg";
                cameraImage.Position = 0;

                using (var stream = await storageFolder.OpenStreamForWriteAsync(filename, CreationCollisionOption.GenerateUniqueName))
                {
                    await cameraImage.CopyToAsync(stream);
                }
            }
            _saved = true;

            return storageFolder.Path + "\\" + filename;
        }
        /*
        /// <summary>
        /// Starts autofocusing, if supported. Capturing buttons are disabled while focusing.
        /// </summary>
        private async Task AutoFocus()
        {
            if (!_capturing && PhotoCaptureDevice.IsFocusSupported(_dataContext.Device.SensorLocation))
            {
                SetScreenButtonsEnabled(false);
                SetCameraButtonsEnabled(false);

                await _dataContext.Device.FocusAsync();

                SetScreenButtonsEnabled(true);
                SetCameraButtonsEnabled(true);

                _capturing = false;
            }
        }
        */

        /// <summary>
        /// Captures a photo. Photo data is stored to DataContext.ImageStream, and application
        /// is navigated to the preview page after capturing.
        /// </summary>
        private async Task Capture()
        {
            //  capture maxFrame images
            while (frameIndex < maxFrame)
            {
                //  don't go to preview
                //  save the image directly
                //bool goToPreview = false;

                if (!_capturing)
                {
                    _capturing = true;

                    MemoryStream stream = new MemoryStream();

                    CameraCaptureSequence sequence = _dataContext.Device.CreateCaptureSequence(1);
                    sequence.Frames[0].CaptureStream = stream.AsOutputStream();

                    await _dataContext.Device.PrepareCaptureSequenceAsync(sequence);
                    await sequence.StartCaptureAsync();

                    _dataContext.ImageStream = stream;

                    _capturing = false;

                    // Defer navigation as it will release the camera device and the
                    // following Device calls must still work.
                    //goToPreview = true;
                }

                _manuallyFocused = false;

                if (PhotoCaptureDevice.IsFocusRegionSupported(_dataContext.Device.SensorLocation))
                {
                    _dataContext.Device.FocusRegion = null;
                }

                FocusIndicator.SetValue(Canvas.VisibilityProperty, Visibility.Collapsed);
                _dataContext.Device.SetProperty(KnownCameraPhotoProperties.LockedAutoFocusParameters, AutoFocusParameters.None);

                //  now we can save the images
                // Reposition ImageStream to beginning, because it has been read already in the OnNavigatedTo method.
                _dataContext.ImageStream.Position = 0;

                MediaLibrary library = new MediaLibrary();
                DateTime t = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Local);
                string fileName = frameIndex + "-" + t.Hour + "-" + t.Minute + "-" + t.Second + "-" + t.Millisecond + ".jpg";
                frameIndex++;
                library.SavePictureToCameraRoll(fileName, _dataContext.ImageStream);

                // There should be no temporary file left behind
                using (var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    var files = isolatedStorage.GetFileNames("CameraExplorer_*.jpg");
                    foreach (string file in files)
                    {
                        isolatedStorage.DeleteFile(file);
                        //System.Diagnostics.Debug.WriteLine("Temp file deleted: " + file);
                    }
                }
                /*
                if (goToPreview)
                {
                    NavigationService.Navigate(new Uri("/PreviewPage.xaml", UriKind.Relative));
                }*/
            }
        }
        private void SaveImageToCameraRoll(int imageHandle, String imageName, Resource imageResource)
        {
            MediaLibrary library = new MediaLibrary();
            MemoryStream targetStream = new MemoryStream();

            int mediaType = MoSync.Constants.MA_MEDIA_TYPE_IMAGE;
            int mediaHandle = imageHandle;
            int eventReturnCode = MoSync.Constants.MA_MEDIA_RES_OK;

            try
            {
                WriteableBitmap data = (WriteableBitmap)imageResource.GetInternalObject();
                data.SaveJpeg(targetStream, data.PixelWidth, data.PixelHeight, 0, 100);
                data = null;

                library.SavePictureToCameraRoll(imageName, targetStream.GetBuffer()).Dispose();
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.ToString());
                eventReturnCode = MoSync.Constants.MA_MEDIA_RES_IMAGE_EXPORT_FAILED;
            }
            finally
            {
                library.Dispose();
                targetStream.Dispose();
                PostMediaEvent(mediaType, mediaHandle, eventReturnCode);
            }
        }
Exemple #15
0
        private async System.Threading.Tasks.Task Capture()
        {
            try
            {
                await camera.FocusAsync();

                MemoryStream imageStream = new MemoryStream();
                imageStream.Seek(0, SeekOrigin.Begin);

                CameraCaptureSequence sequence = camera.CreateCaptureSequence(1);
                sequence.Frames[0].CaptureStream = imageStream.AsOutputStream();

                await camera.PrepareCaptureSequenceAsync(sequence);
                await sequence.StartCaptureAsync();

                camera.SetProperty(
                KnownCameraPhotoProperties.LockedAutoFocusParameters,
                AutoFocusParameters.None);

                MediaLibrary library = new MediaLibrary();

                EditingSession session = new EditingSession(imageStream.GetWindowsRuntimeBuffer());

                using (session)
                {
                    session.AddFilter(FilterFactory.CreateSketchFilter(SketchMode.Gray));
                    IBuffer data = await session.RenderToJpegAsync();
                    library.SavePictureToCameraRoll(FileNamePrefix
                                + DateTime.Now.ToString() + ".jpg",
                                data.AsStream());
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Failed to save the image to camera roll: " + ex.ToString());
            }
        }
 /// <summary>
 /// カメラロールへファイルを保存する
 /// 既存の同名ファイルが存在している場合はファイルを上書きする
 /// </summary>
 /// <param name="fileName">拡張子を含むファイル名</param>
 /// <param name="stream">保存するデータのストリーム</param>
 public static void SaveToCameraRoll(this Stream stream, string fileName)
 {
     stream.Position = 0;
     using (var ml = new MediaLibrary())
     {
         ml.SavePictureToCameraRoll(fileName, stream);
     }
 }
        private async void ApplicationBarIconButton_All(object sender, EventArgs e)
        {
            sFace.Position = 0;
            sBackground.Position = 0;

            IBuffer result;
            using (var faceSource = new StreamImageSource(sFace))
            using (var faceReframing = new FilterEffect(faceSource))
            using (var source = new StreamImageSource(sBackground))
            using (var effect = new FilterEffect(source))
            using (var renderer = new JpegRenderer(effect))
            {

                

                var size = gestureBackground.ImageSize;
                var Facesize = gestureFace.ImageSize;

                //target scale
                var scale = gestureFace.Scale / gestureBackground.Scale;
                //target angle
                var angle = gestureFace.Angle - gestureBackground.Angle;


                //translation between image center and background position
                var backgroundTranslation = new Point(size.Width / 2 - gestureBackground.Pos.X, size.Height / 2 - gestureBackground.Pos.Y);

                //convert translation to Face referential translation
                CompositeTransform gestureTransform = new CompositeTransform();
                gestureTransform.ScaleX = gestureTransform.ScaleY = scale;
                gestureTransform.Rotation = angle;
                var translation = gestureTransform.Inverse.Transform(backgroundTranslation);

                //target position
                var posX = gestureFace.Pos.X + translation.X;
                var posY = gestureFace.Pos.Y + translation.Y;



                var currentSize = new Windows.Foundation.Size(size.Width / scale, size.Height / scale);
                var corner = new Windows.Foundation.Point(posX - currentSize.Width / 2, posY - currentSize.Height / 2);
                var reframing = new ReframingFilter(new Windows.Foundation.Rect(corner, currentSize), -angle);

                //face reframing => blend input
                faceReframing.Filters = new IFilter[] { reframing };
                effect.Filters = new IFilter[] { new BlendFilter(faceReframing) };//


                result = await renderer.RenderAsync();
            }

            using (var media = new MediaLibrary())
                media.SavePictureToCameraRoll("test", result.ToArray());
        }
        private async void ApplicationBarIconButton_reframing(object sender, EventArgs e)
        {
            sFace.Position = 0;
            sBackground.Position = 0;

            IBuffer result;
            using (var faceSource = new StreamImageSource(sFace))
            using (var faceReframing = new FilterEffect(faceSource))
            using (var source = new StreamImageSource(sBackground))
            using (var effect = new FilterEffect(source) )
            using (var renderer = new JpegRenderer(effect))
            {

                //face reframing => blend input
                faceReframing.Filters = new IFilter[] { gestureFace.CreateReframingFilter() } ;

                //face
                effect.Filters = new IFilter[] { 
                    gestureBackground.CreateReframingFilter() ,//background reframing
                    new BlendFilter(faceReframing) //blending


                };


                result = await renderer.RenderAsync();
            }

            using (var media = new MediaLibrary())
                media.SavePictureToCameraRoll("test", result.ToArray());

        }
 void cam_CaptureImageAvailable(object sender, ContentReadyEventArgs e)
 {
     MediaLibrary library = new MediaLibrary();
     string fileName = Guid.NewGuid().ToString() + ".jpg";
     library.SavePictureToCameraRoll(fileName, e.ImageStream);
     Dispatcher.BeginInvoke(() => msg.Text = "照片保存成功");
 }
Exemple #20
0
    private async void TakePicture() {
      if (!_capturing) {
        _capturing = true;
        CameraCaptureSequence cameraCaptureSequence = _camera.CreateCaptureSequence(1);

        var stream = new MemoryStream();
        cameraCaptureSequence.Frames[0].CaptureStream = stream.AsOutputStream();

        await _camera.PrepareCaptureSequenceAsync(cameraCaptureSequence);
        await cameraCaptureSequence.StartCaptureAsync();

        var effect = await _cameraEffect.ApplyEffect(stream);
        // store the processed image

        var library = new MediaLibrary();
        library.SavePictureToCameraRoll(String.Format("WP8_{0:yyyyMMdd_hhmmss}.jpg", DateTime.Now), effect);

        //// store the original
        //stream.Seek(0, SeekOrigin.Begin);
        //var library = new MediaLibrary();
        //library.SavePictureToCameraRoll("pic1.jpg", stream);
        _capturing = false;
      }
    }
Exemple #21
0
        private void LayOutToBitMapImage()
        {
            // create a WriteableBitmap
            _writableBitmapOfScreen = new WriteableBitmap(
                (int)this.LayoutRoot.ActualWidth,
                (int)this.LayoutRoot.ActualHeight);

            // render the visual element to the WriteableBitmap
            _writableBitmapOfScreen.Render(this.LayoutRoot, new TranslateTransform());

            // request an redraw of the bitmap
            _writableBitmapOfScreen.Invalidate();

            // Get an Image Stream
            MemoryStream ms_Image = new MemoryStream();

            // write the image into the stream
            System.Windows.Media.Imaging.Extensions.SaveJpeg(_writableBitmapOfScreen, ms_Image, _writableBitmapOfScreen.PixelWidth, _writableBitmapOfScreen.PixelHeight, 0, 100);
            // reset the stream pointer to the beginning

            ms_Image.Seek(0, 0);

            //JpegInfo info = ExifReader.ReadJpeg(ms_Image, "tomatoes");
            if (_captureOrientation == PageOrientation.LandscapeLeft)
            {
                Stream temp = RotateStream(ms_Image, 90);
                temp.Seek(0, 0);
                ms_Image.Close();

                var library = new MediaLibrary();
                library.SavePictureToCameraRoll("tomato", temp);
                temp.Close();

            }
            else
            {
                Stream temp = RotateStream(ms_Image, 270);
                temp.Seek(0, 0);
                ms_Image.Close();

                var library = new MediaLibrary();
                library.SavePictureToCameraRoll("tomato", temp);
                temp.Close();
            }
        }
        private async Task SaveCapturedPhotoToLibrary(MemoryStream fullStream, MemoryStream previewStream)
        {
            try
            {
                Stream thumbnailStream = previewStream;
                if (PerfectCamera.DataContext.Instance.CameraType == PerfectCameraType.Selfie)
                {
                    thumbnailStream = await _cameraEffect.ApplyEffect(previewStream);
                }
                if (thumbnailStream != null)
                {
                    thumbnailStream.Position = 0;
                    ImageBrush brush = new ImageBrush();
                    brush.Stretch = Stretch.UniformToFill;
                    var bmp = new BitmapImage();
                    bmp.SetSource(thumbnailStream);
                    brush.ImageSource = bmp;
                    PreviewThumbnailButton.Background = brush;
                }

                Stream capturedStream = fullStream;
                if (PerfectCamera.DataContext.Instance.CameraType == PerfectCameraType.Selfie)
                {
                    capturedStream = await _cameraEffect.ApplyEffect(fullStream);
                }
                if (capturedStream != null)
                {
                    capturedStream.Position = 0;
                    using (MediaLibrary library = new MediaLibrary())
                    {
                        library.SavePictureToCameraRoll(FileNamePrefix
                                + DateTime.Now.ToString() + ".jpg", capturedStream);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("save ex: {0}", ex.Message);
            }
        }
Exemple #23
0
        public Task<HttpResponseMessage> UploadPhotoAsync(Uri location, string secret, Stream photo)
        {
            using(MediaLibrary ml = new MediaLibrary())
            {
                photo.Position = 0;
                ml.SavePictureToCameraRoll(location.ToString(), photo);
            }

            return Task.FromResult<HttpResponseMessage>(new HttpResponseMessage());
        }
        private void client_AuthenticateCompleted(object sender, RequestCompletedEventArgs e)
        {
            // unregister previous event handler
            App.MetrocamService.AuthenticateCompleted -= client_AuthenticateCompleted;

            WriteableBitmap bitmap = new WriteableBitmap((BitmapSource)EditPicture.editedPicture.Source);

            var width = bitmap.PixelWidth * 2;
            var height = bitmap.PixelHeight * 2;
            //var resultPixels = effect.Process(bitmap.Pixels, width, height);

            ms = new MemoryStream();
            bitmap.SaveJpeg(ms, width, height, 0, 100);
            ms.Seek(0, SeekOrigin.Begin);

            /******
             *
             *  save original photo to phone
             *
             */
            long timestamp = DateTime.Now.ToFileTime();
            String originalFilename = "MetrocamOriginal_" + timestamp.ToString() + ".jpg";

            var myStore = IsolatedStorageFile.GetUserStoreForApplication();

            var lib = new MediaLibrary();

            if (Settings.saveOriginal.Value && MainPage.tookPhoto)
            {
                IsolatedStorageFileStream myFileStream = myStore.CreateFile(originalFilename);
                WriteableBitmap w = new WriteableBitmap((BitmapSource)MainPage.bmp);
                w.SaveJpeg(myFileStream, w.PixelWidth, w.PixelHeight, 0, 100);
                myFileStream.Close();

                myFileStream = myStore.OpenFile(originalFilename, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                lib.SavePictureToCameraRoll(originalFilename, myFileStream);
            }

            // upload the image
            App.MetrocamService.UploadPictureCompleted += new RequestCompletedEventHandler(client_UploadPictureCompleted);
            App.MetrocamService.UploadPicture(ms);
        }
        /// <summary>
        /// Asynchronously saves a low resolution version of the photo to MediaLibrary and if the photo is too large to be saved
        /// to MediaLibrary as is also saves the original high resolution photo to application's local storage so that the
        /// high resolution version is not lost.
        /// </summary>
        public async Task SaveAsync()
        {
            if (_image != null && _image.Length > 0 && LibraryPath == null)
            {
                var buffer = StreamToBuffer(_image);

                AutoResizeConfiguration resizeConfiguration = null;

                using (var source = new BufferImageSource(buffer))
                {
                    var info = await source.GetInfoAsync();

                    if (info.ImageSize.Width * info.ImageSize.Height > LibraryMaxArea)
                    {
                        var compactedSize = CalculateSize(info.ImageSize, LibraryMaxSize, LibraryMaxArea);

                        resizeConfiguration = new AutoResizeConfiguration(LibraryMaxBytes, compactedSize,
                            new Size(0, 0), AutoResizeMode.Automatic, 0, ColorSpace.Yuv420);
                    }
                }

                var filenameBase = "photoinspector";

                if (_original != null)
                {
                    if (_originalPath != null)
                    {
                        var originalPathParts = _originalPath.Split(new char[] { '_', '.' }, StringSplitOptions.RemoveEmptyEntries);

                        filenameBase += '_' + originalPathParts[1];
                    }
                    else
                    {
                        filenameBase += '_' + DateTime.UtcNow.Ticks.ToString();

                        using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            if (!store.DirectoryExists(Mapping.ORIGINALS_PATH))
                            {
                                store.CreateDirectory(Mapping.ORIGINALS_PATH);
                            }

                            var originalPath = Mapping.ORIGINALS_PATH + @"\" + filenameBase + @".jpg";

                            using (var file = store.CreateFile(originalPath))
                            {
                                _original.Position = 0;
                                _original.CopyTo(file);

                                file.Flush();

                                OriginalPath = originalPath;
                            }
                        }
                    }
                }

                filenameBase += '_' + DateTime.UtcNow.Ticks.ToString();

                if (resizeConfiguration != null)
                {
                    // Store high resolution original to application local storage

                    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (!store.DirectoryExists(Mapping.LOCALS_PATH))
                        {
                            store.CreateDirectory(Mapping.LOCALS_PATH);
                        }

                        var localPath = Mapping.LOCALS_PATH + @"\" + filenameBase + @".jpg";

                        using (var file = store.CreateFile(localPath))
                        {
                            _image.Position = 0;
                            _image.CopyTo(file);

                            file.Flush();

                            LocalPath = localPath;
                        }
                    }

                    // Compact the buffer for saving to the library

                    buffer = await Nokia.Graphics.Imaging.JpegTools.AutoResizeAsync(buffer, resizeConfiguration);
                }

                using (var libraryImage = buffer.AsStream())
                {
                    libraryImage.Position = 0;

                    using (var library = new MediaLibrary())
                    {
                        using (var picture = library.SavePictureToCameraRoll(filenameBase, libraryImage))
                        {
                            LibraryPath = picture.GetPath();
                        }
                    }
                }
            }
        }
        private void SavePicture()
        {
            String tempJPEG = "TempJPEG";

            var myStore = IsolatedStorageFile.GetUserStoreForApplication();
            if (myStore.FileExists(tempJPEG))
            {
                myStore.DeleteFile(tempJPEG);
            }

            IsolatedStorageFileStream myFileStream = myStore.CreateFile(tempJPEG);
            VideoImage.ImageSource.SaveJpeg(myFileStream, VideoImage.ImageSource.PixelWidth, VideoImage.ImageSource.PixelHeight, 0, 85);
            myFileStream.Close();


            // Create a new stream from isolated storage, and save the JPEG file to the media library on Windows Phone.
            myFileStream = myStore.OpenFile(tempJPEG, FileMode.Open, FileAccess.Read);

            // Save the image to the camera roll or saved pictures album.
            MediaLibrary library = new MediaLibrary();
            // Save the image to the camera roll album.
            Picture pic = library.SavePictureToCameraRoll("SavedPicture.jpg", myFileStream);
            MessageBox.Show("Image saved to camera roll album");
            myFileStream.Close();

        }