Beispiel #1
0
        public void onTaskCompleted(object sender, PhotoResult e)
        {
            if (e.Error != null)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR));
                return;
            }

            switch (e.TaskResult)
            {
            case TaskResult.OK:
                try
                {
                    string imagePathOrContent = string.Empty;

                    if (cameraOptions.DestinationType == FILE_URI)
                    {
                        WriteableBitmap image = PictureDecoder.DecodeJpeg(e.ChosenPhoto);
                        imagePathOrContent = this.SaveImageToLocalStorage(image, Path.GetFileName(e.OriginalFileName));
                    }
                    else if (cameraOptions.DestinationType == DATA_URL)
                    {
                        imagePathOrContent = this.GetImageContent(e.ChosenPhoto);
                    }
                    else
                    {
                        DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Incorrec option: destinationType"));
                        return;
                    }

                    DispatchCommandResult(new PluginResult(PluginResult.Status.OK, imagePathOrContent));
                }
                catch (Exception ex)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Error retrieving image."));
                }
                break;

            case TaskResult.Cancel:
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Selection cancelled."));
                break;

            default:
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Selection did not complete!"));
                break;
            }
        }
        /// <summary>
        /// User would like to load an existing photo from library
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void load_click(object sender, EventArgs e)
        {
            PhotoChooserTask photoChooserTask;

            photoChooserTask = new PhotoChooserTask();

            //picture loaded
            photoChooserTask.Completed += (s, ev) =>
            {
                if (ev.TaskResult == TaskResult.OK)
                {
                    Renderer.LoadNewImage(GPUImageGame.InitialFilters[0], PictureDecoder.DecodeJpeg(ev.ChosenPhoto), -1);
                }
            };

            photoChooserTask.Show();
        }
Beispiel #3
0
        public static byte[] CreateThumb(byte[] image, int rectangleSize, int targetQuality, out int targetHeight, out int targetWidth)
        {
            var stream          = new MemoryStream(image);
            var writeableBitmap = PictureDecoder.DecodeJpeg(stream);

            var maxDimension = Math.Max(writeableBitmap.PixelWidth, writeableBitmap.PixelHeight);
            var scale        = (double)rectangleSize / maxDimension;

            targetHeight = (int)(writeableBitmap.PixelHeight * scale);
            targetWidth  = (int)(writeableBitmap.PixelWidth * scale);

            var outStream = new MemoryStream();

            writeableBitmap.SaveJpeg(outStream, targetWidth, targetHeight, 0, targetQuality);

            return(outStream.ToArray());
        }
        private WriteableBitmap DecodeImage(Stream imageStream, int angle)
        {
            WriteableBitmap source = PictureDecoder.DecodeJpeg(imageStream);

            switch (angle)
            {
            case 90:
            case 270:
                return(RotateBitmap(source, source.PixelHeight, source.PixelWidth, angle));

            case 180:
                return(RotateBitmap(source, source.PixelWidth, source.PixelHeight, angle));

            default:
                return(source);
            }
        }
Beispiel #5
0
        public static WriteableBitmap GetImage(string filePath)
        {
            using (var isoStore = IsolatedStorageFile.GetUserStoreForApplication())
            {
                WriteableBitmap image = null;

                if (isoStore.FileExists(filePath))
                {
                    using (var imageStream = isoStore.OpenFile(filePath, FileMode.Open, FileAccess.Read))
                    {
                        image = PictureDecoder.DecodeJpeg(imageStream);
                    }
                }

                return(image);
            }
        }
Beispiel #6
0
        /// <summary>
        /// Extract file from Isolated Storage as WriteableBitmap object
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        private WriteableBitmap ExtractImageFromLocalStorage(string filePath)
        {
            try
            {
                var isoFile = IsolatedStorageFile.GetUserStoreForApplication();

                using (var imageStream = isoFile.OpenFile(filePath, FileMode.Open, FileAccess.Read))
                {
                    var imageSource = PictureDecoder.DecodeJpeg(imageStream);
                    return(imageSource);
                }
            }
            catch (Exception)
            {
                return(null);
            }
        }
Beispiel #7
0
 public static WriteableBitmap ReadImageFromIsolatedStorageToWriteableBitmap(string fileName)
 {
     using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
     {
         if (myIsolatedStorage.FileExists(fileName))
         {
             using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(fileName, FileMode.Open, FileAccess.Read))
             {
                 // Decode the JPEG stream.
                 return(PictureDecoder.DecodeJpeg(fileStream));
             }
         }
         else
         {
             return(ReadImageFromContent("./Images/LittleDude.jpg"));
         }
     }
 }
        void chooserTask_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                currentImage = PictureDecoder.DecodeJpeg(e.ChosenPhoto);

                photoContainer.Fill = new ImageBrush {
                    ImageSource = currentImage
                };
                imageDetails.Text  = string.Format("Image from {0}\n", sender.GetType().Name);
                imageDetails.Text += string.Format("Original filename:\n{0}", e.OriginalFileName);
            }
            else
            {
                photoContainer.Fill = new SolidColorBrush(Colors.Gray);
                imageDetails.Text   = e.TaskResult.ToString();
            }
        }
Beispiel #9
0
        public async Task DownloadHeaderImage()
        {
            if (String.IsNullOrEmpty(HeaderImageUrl))
            {
                return;
            }

            IsBackgroundProccessRunning = true;

            var imageStream = await ConnectionAgent.Current.GetImageStream(HeaderImageUrl);

            if (imageStream != null)
            {
                HeaderImage = PictureDecoder.DecodeJpeg(imageStream);
            }

            IsBackgroundProccessRunning = false;
        }
 /*Questa funzione permette di salvare l'immagine nel dispositivo. */
 private void TaskCompleted(object sender, PhotoResult photo_result)
 {
     byte[] _local_image;
     //se lo stream dei dati riguardo alla foto scattata non è nullo si prosegue con il salvataggio.
     if (photo_result.ChosenPhoto != null)
     {
         //creo lo stream dove salvare i dati
         _local_image = new byte[(int)photo_result.ChosenPhoto.Length];
         //lo stream dei dati sarà salvato in _local_image
         photo_result.ChosenPhoto.Read(_local_image, 0, _local_image.Length);
         //mi posiziono all'inizio dello stream dei dati per il salvataggio
         photo_result.ChosenPhoto.Seek(0, System.IO.SeekOrigin.Begin);
         //effettuo la conversione in un formato compatibile e leggibile
         var bitmapImage = PictureDecoder.DecodeJpeg(photo_result.ChosenPhoto);
         //visualizzo nel panello una preview dell'immagine appena salvata
         captured_image.Source = bitmapImage;
     }
 }
Beispiel #11
0
        /// <summary>
        /// Converts the picture of a contact (an ImageStream) into an Image object.
        /// </summary>
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            Contact c = value as Contact;

            if (c == null)
            {
                return(null);
            }

            Stream imgStream = c.GetPicture();

            if (imgStream != null)
            {
                return(PictureDecoder.DecodeJpeg(imgStream));
            }

            return(null);
        }
Beispiel #12
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            string picName;

            if (NavigationContext.QueryString.TryGetValue("picName", out picName))
            {
                FileStream isoStream = storage.OpenFile(picName, FileMode.Open, FileAccess.Read);

                /*long len = isoStream.Length;
                 * BitmapImage b = new BitmapImage();
                 * b.SetSource(isoStream);*/
                //picture.Source = b;
                picture.Source = PictureDecoder.DecodeJpeg(isoStream, 1280, 1280);
                isoStream.Dispose();
                imageName = picName;
            }
        }
Beispiel #13
0
        public void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            Thread.Sleep(30);
            string[]   fileNames = storage.GetFileNames();
            FileStream isoStream = storage.OpenFile(fileNames[i], FileMode.Open, FileAccess.Read);

            photoList.Dispatcher.BeginInvoke(() =>
            {
                Image image   = new Image();
                image.Source  = PictureDecoder.DecodeJpeg(isoStream, 155, 155);
                image.Width   = 142;
                image.Height  = 142;
                image.Stretch = System.Windows.Media.Stretch.UniformToFill;
                image.Margin  = new Thickness(5, 0, 5, 10);
                photoList.Items.Add(image);
                isoStream.Dispose();
            });
        }
Beispiel #14
0
        public static byte[] ResizeImageWinPhone(byte[] imageData, float width)
        {
            byte[] resizedData;

            using (MemoryStream streamIn = new MemoryStream(imageData))
            {
                float height = (float)(width * imageData.Height / imageData.Width);

                WriteableBitmap bitmap = PictureDecoder.DecodeJpeg(streamIn, (int)width, (int)height);

                using (MemoryStream streamOut = new MemoryStream())
                {
                    bitmap.SaveJpeg(streamOut, (int)width, (int)height, 0, 100);
                    resizedData = streamOut.ToArray();
                }
            }
            return(resizedData);
        }
Beispiel #15
0
        private void BlurPage_LayoutUpdated(object sender, EventArgs e)
        {
            if (this.loadImageOnLayoutUpdate && this.pageNavigationComplete)
            {
                try
                {
                    using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        string file_name = "image.jpg";

                        if (store.FileExists(file_name))
                        {
                            using (IsolatedStorageFileStream stream = store.OpenFile(file_name, FileMode.Open, FileAccess.Read))
                            {
                                WriteableBitmap bitmap = PictureDecoder.DecodeJpeg(stream, MAX_LOADED_WIDTH, MAX_LOADED_HEIGHT);

                                LoadImage(bitmap);
                            }

                            store.DeleteFile(file_name);
                        }
                    }
                }
                catch (Exception ex)
                {
                    ThreadPool.QueueUserWorkItem((stateInfo) =>
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(delegate()
                        {
                            try
                            {
                                MessageBox.Show(AppResources.MessageBoxMessageImageOpenError + " " + ex.Message.ToString(), AppResources.MessageBoxHeaderError, MessageBoxButton.OK);
                            }
                            catch (Exception)
                            {
                                // Ignore
                            }
                        });
                    });
                }

                this.loadImageOnLayoutUpdate = false;
            }
        }
Beispiel #16
0
        public void GetScreenShots()
        {
            try
            {
                PictureAlbumCollection allAlbums = _mediaLibrary.RootPictureAlbum.Albums;
                ScreenShots.Clear();

                foreach (var album in allAlbums)
                {
                    if (album.Name.ToUpper().Contains("SCREENSHOT"))
                    {
                        PictureCollection screenShots = album.Pictures;

                        foreach (var picture in screenShots)
                        {
                            Stream picToDisplay = picture.GetImage();

                            BitmapImage bmImage = new BitmapImage();
                            bmImage.SetSource(picToDisplay);

                            var imageToShow = new Image
                            {
                                Source = PictureDecoder.DecodeJpeg(picToDisplay, picture.Width, picture.Height)
                            };


                            ScreenShots.Add(new ScreenShot(picture.Name, new Uri(MediaLibraryExtensions.GetPath(picture), UriKind.Absolute), imageToShow));
                        }
                    }
                }

                if (ScreenShots.Count() >= 1)
                {
                    SelectedScreenShot = ScreenShots[ScreenShots.Count - 1];
                }
                else
                {
                    NoScreenShotVisibility = Visibility.Visible;
                }
            }
            catch (Exception ex)
            {
            }
        }
Beispiel #17
0
        void ctask_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK && e.ChosenPhoto != null)
            {
                //Take JPEG stream and decode into a WriteableBitmap object
                CapturedImage = PictureDecoder.DecodeJpeg(e.ChosenPhoto);
                ImageBrush brush = new ImageBrush();
                brush.ImageSource = CapturedImage;
                //Collapse visibility on the progress bar once writeable bitmap is visible.
                //progressBar1.Visibility = Visibility.Collapsed;
                btn_Pic.Background = brush;
            }
            else
            {
                //textStatus.Text = "You decided not to take a picture.";
            }

            imgPicture.Source = CapturedImage;
        }
 void task_Completed(object sender, PhotoResult e)
 {
     if (e.ChosenPhoto != null)
     {
         if (e.TaskResult == TaskResult.OK)
         {
             try
             {
                 string          imagePathOrContent = string.Empty;
                 WriteableBitmap image = PictureDecoder.DecodeJpeg(e.ChosenPhoto);
                 imgphoto.Source    = image;
                 imagePathOrContent = this.SaveImageToLocalStorage(image, System.IO.Path.GetFileName(e.OriginalFileName));
             }
             catch (Exception)
             {
             }
         }
     }
 }
        /// <summary>
        /// User wants to take a new picture with the camera
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void newImg_click(object sender, EventArgs e)
        {
            ctask = new CameraCaptureTask();

            //Photo captured
            ctask.Completed += (s, ev) =>
            {
                if (ev.TaskResult == TaskResult.OK)
                {
                    //load to initial filter
                    if (GPUImageGame.InitialFilters.Count == 1)
                    {
                        Renderer.LoadNewImage(GPUImageGame.InitialFilters[0], PictureDecoder.DecodeJpeg(ev.ChosenPhoto));
                    }
                }
            };

            ctask.Show();
        }
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string fileName = value as string;

        if (fileName != null)
        {
            WriteableBitmap bitmap = new WriteableBitmap(200, 200);
            using (IsolatedStorageFile myIsoStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream fileStream = myIsoStorage.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                {
                    //StreamResourceInfo sri = Application.GetResourceStream(fileStream);
                    bitmap = PictureDecoder.DecodeJpeg(fileStream);
                }
            }
            return(bitmap);
        }
        return(null);
    }
 private void LoadFromLocalStorage()
 {
     try
     {
         WriteableBitmap bitmap = new WriteableBitmap(800, 800);
         using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
         {
             using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("MyImage.jpg", FileMode.Open, FileAccess.Read))
             {
                 // Decode the JPEG stream.
                 bitmap = PictureDecoder.DecodeJpeg(fileStream);
             }
         }
         MyImage.Source = bitmap;
     }
     catch (Exception e)
     {
         System.Diagnostics.Debug.WriteLine(e.Message);
     }
 }
 async void Open_Click(object sender, EventArgs e)
 {
     try
     {
         StorageFolder localFolder = ApplicationData.Current.LocalFolder;
         using (Stream imageStream = await localFolder.OpenStreamForReadAsync("custom-photo.jpg"))
         {
             currentImage        = PictureDecoder.DecodeJpeg(imageStream);
             photoContainer.Fill = new ImageBrush {
                 ImageSource = currentImage
             };
         }
         imageDetails.Text = string.Format("Image loaded from filename:\ncustom-photo.jpg");
     }
     catch (FileNotFoundException)
     {
         photoContainer.Fill = new SolidColorBrush(Colors.Gray);
         imageDetails.Text   = "Image not found!";
     }
 }
 private List<ImageViewModel> LoadImages()
 {
     List<ImageViewModel> images = new List<ImageViewModel>();
     
     // Part of the original code.
     foreach (string fileName in fileStorage.GetFileNames("images//*.*"))
     {
         if (fileName == null)
             break;
         string filepath = System.IO.Path.Combine("images", fileName);
         using (IsolatedStorageFileStream imageStream = fileStorage.OpenFile(filepath,FileMode.Open,FileAccess.Read))
         {
             var imageSource = PictureDecoder.DecodeJpeg(imageStream);
             BitmapImage bitmapImage = new BitmapImage();
             bitmapImage.SetSource(imageStream);
             
             ImageViewModel imageViewModel = new ImageViewModel(fileName, bitmapImage);
             images.Add(imageViewModel);
         }
     }
 }
Beispiel #24
0
        public static async Task <List <UIElement> > ConvertHtmlToXaml(string htmlData)
        {
            var doc = new HtmlDocument();

            doc.LoadHtml(htmlData);

            var nodes = doc.DocumentNode.DescendantNodes().ToList();

            var elements = new List <UIElement>();

            foreach (var htmlNode in nodes)
            {
                if (htmlNode.Name == "#text")
                {
                    var text = new TextBlock();
                    text.TextWrapping = TextWrapping.Wrap;
                    text.Text         = htmlNode.InnerText;
                    elements.Add(text);
                }
                else if (htmlNode.Name == "p")
                {
                    var text = new TextBlock();
                    text.Inlines.Add(new LineBreak());
                    elements.Add(text);
                }
                else if (htmlNode.Name == "img")
                {
                    var src = Regex.Match(htmlNode.OuterHtml, "<img src=\"(.+?)\"").Groups[1].Value;

                    var image       = new Image();
                    var imageStream = await ConnectionAgent.Current.GetImageStream(src);

                    image.Source = PictureDecoder.DecodeJpeg(imageStream);

                    elements.Add(image);
                }
            }

            return(elements);
        }
        private void photoChooserTask_Completed(object sender, PhotoResult e)
        {
            if (e != null && e.ChosenPhoto != null)
            {
                if (e.TaskResult == TaskResult.OK)
                {
                    WriteableBitmap bitmap = PictureDecoder.DecodeJpeg(e.ChosenPhoto, MAX_LOADED_WIDTH, MAX_LOADED_HEIGHT);

                    LoadImage(bitmap);
                }
                else
                {
                    this.loadImageCancelled = true;
                }

                e.ChosenPhoto.Dispose();
            }
            else
            {
                this.loadImageCancelled = true;
            }
        }
        WriteableBitmap DecodeJpeg(Stream imageStream)
        {
            WriteableBitmap source = PictureDecoder.DecodeJpeg(imageStream);

            imageStream.Position = 0;
            ushort orientation = GetExifOrientation(imageStream);

            switch (orientation)
            {
            case 3:
                return(RotateBitmap(source, source.PixelWidth, source.PixelHeight, 180));

            case 6:
                return(RotateBitmap(source, source.PixelHeight, source.PixelWidth, 90));

            case 8:
                return(RotateBitmap(source, source.PixelHeight, source.PixelWidth, 270));

            default:
                return(source);
            }
        }
Beispiel #27
0
        private async Task Initialise()
        {
            if (ConnectionAgent.Current.IsAuthenticated)
            {
                App.MainPageModel = await ConnectionAgent.Current.GetMainPage();

                _navigationService.NavigateTo(ViewModelLocator.MainPageUri);
                //NavigationService.Navigate(new Uri("/View/Test.xaml", UriKind.Relative));
            }
            else
            {
                var loginPageModel = await ConnectionAgent.Current.GetLoginPage();

                var imageStream = await ConnectionAgent.Current.GetImageStream(loginPageModel.CaptchaImageUrl);

                var loginPageViewModel = SimpleIoc.Default.GetInstance <LoginViewModel>();
                loginPageViewModel.CaptchaImage = PictureDecoder.DecodeJpeg(imageStream);
                loginPageViewModel.LoginCode    = loginPageModel.LoginCode;

                _navigationService.NavigateTo(ViewModelLocator.LoginPageUri);
            }
        }
        // Sample code for building a localized ApplicationBar
        //private void BuildLocalizedApplicationBar()
        //{
        //    // Set the page's ApplicationBar to a new instance of ApplicationBar.
        //    ApplicationBar = new ApplicationBar();

        //    // Create a new button and set the text value to the localized string from AppResources.
        //    ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative));
        //    appBarButton.Text = AppResources.AppBarButtonText;
        //    ApplicationBar.Buttons.Add(appBarButton);

        //    // Create a new menu item with the localized string from AppResources.
        //    ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
        //    ApplicationBar.MenuItems.Add(appBarMenuItem);
        //}

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (State.ContainsKey("customCamera"))
            {
                State.Remove("customCamera");
                InitializeCamera();
            }

            IDictionary <string, string> queryStrings = NavigationContext.QueryString;

            string fileId = null;
            string source = null;

            // Photos_Extra_Viewer is deprecated
            //if (queryStrings.ContainsKey("token"))
            //{
            //    token = queryStrings["token"];
            //    source = "Photos_Extra_Viewer";
            //}
            //else
            if (queryStrings.ContainsKey("Action") && queryStrings.ContainsKey("FileId"))
            {
                fileId = queryStrings["FileId"];
                source = queryStrings["Action"];
            }

            if (!string.IsNullOrEmpty(fileId))
            {
                MediaLibrary mediaLib = new MediaLibrary();
                Picture      picture  = mediaLib.GetPictureFromToken(fileId);

                currentImage        = PictureDecoder.DecodeJpeg(picture.GetImage());
                photoContainer.Fill = new ImageBrush {
                    ImageSource = currentImage
                };
                imageDetails.Text = string.Format("Image from {0}.\nPicture name:\n{1}\nMedia library token:\n{2}",
                                                  source, picture.Name, fileId);
            }
        }
Beispiel #29
0
        // AACODE: Get image from photo chooser
        private void photoChooserTask_Completed(Object sender, PhotoResult e)
        {
            try
            {
                // If a photo has been selected then take action, otherwise do nothing.
                if (e.ChosenPhoto != null)
                {
                    App.gCapturedImage = PictureDecoder.DecodeJpeg(e.ChosenPhoto);

                    // If photo has been chosen, navigate to ChannelSplitter Page.
                    NavigationService.Navigate(new Uri(App.GetDynamicUri("MainPage", "ProcessImage"), UriKind.Relative));
                }
            }
            catch (Exception ex)
            {
                this.Dispatcher.BeginInvoke(delegate()
                {
                    // TODO: Add erro
                    // txtDebug.Text = ex.Message;
                });
            }
        }
Beispiel #30
0
        void pc_Completed(object sender, PhotoResult e)
        {
            try
            {
                string    originalFileName = Path.GetFileName(e.OriginalFileName);
                SavePhoto savePhoto        = new SavePhoto();
                savePhoto.SaveImageToIsolatedStorage(e.ChosenPhoto, originalFileName, 0, 100);
                savePhoto = null;

                AdvancedTextIO advancedTextIO = new AdvancedTextIO();
                string[]       fileNames      = storage.GetFileNames();
                short          lineNumber     = advancedTextIO.FindTextInLine(originalFileName);

                if (usingTextView == false)
                {
                    FileStream isoStream = storage.OpenFile(fileNames[lineNumber], FileMode.Open, FileAccess.Read);
                    photoList.Dispatcher.BeginInvoke(() =>
                    {
                        Image image   = new Image();
                        image.Source  = PictureDecoder.DecodeJpeg(isoStream, 155, 155);
                        image.Width   = 142;
                        image.Height  = 142;
                        image.Stretch = System.Windows.Media.Stretch.UniformToFill;
                        image.Margin  = new Thickness(5, 0, 5, 10);
                        photoList.Items.Insert(lineNumber, image);
                        isoStream.Dispose();
                    });
                }
                else
                {
                    photoList.ItemsSource = fileNames;
                }

                advancedTextIO = null;
                GC.Collect();
            }
            catch {}
        }