Beispiel #1
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)
            {
            }
        }
        private void CartoonPage_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;
            }
        }
 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)
             {
             }
         }
     }
 }
        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;
        }
        /// <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 #10
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);
        }
        // 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 #12
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 #13
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);
            }
        }
        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);
            }
        }
        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;
            }
        }
Beispiel #16
0
        public async void RefreshFullBitmap()
        {
            Debug.WriteLine("RefreshFullBitmap : " + PathToFullBitmap);
            if (string.IsNullOrEmpty(PathToFullBitmap) || isRefreshingFullBitmap)
            {
                return;
            }

            isRefreshingFullBitmap = true;
            byte[] bitmap = null;
            using (var fileStream = await LoadImageAsync(this.PathToFullBitmap).ConfigureAwait(false))
            {
                if (fileStream != null)
                {
                    bitmap = ReadFully(fileStream);
                }
            }

            await Deployment.Current.Dispatcher.InvokeAsync(() =>
            {
                WriteableBitmap bi = null;

                if (bitmap != null)
                {
                    bi = PictureDecoder.DecodeJpeg(new MemoryStream(bitmap));
                    if (this.isPixelized)
                    {
                        Debug.WriteLine("Pixelise " + this.PathToFullBitmap);
                        bi = Pixelate(bi, this.FloutedAreas, PIXELISATION_FACTOR);
                    }
                }

                //return bi;
                this.fullImage = bi;
                NotifyPropertyChanged(m => m.FullImage);
                isRefreshingFullBitmap = false;
            }).ConfigureAwait(false);
        }
Beispiel #17
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 {}
        }
Beispiel #18
0
        void photo_Completed(object sender, PhotoResult e)
        {
            if (e.ChosenPhoto != null)
            {
                bitmapImage   = PictureDecoder.DecodeJpeg(e.ChosenPhoto);
                image1.Source = bitmapImage;

                // No effect is applied
                isFishEyeEffect   = false;
                isGrayScaleEffect = false;
                isInvertEffect    = false;
                isBinaryEffect    = false;
                textBox1.Text     = "";
                // After the image is loaded, the buttons are activated
                (ApplicationBar.Buttons[1] as ApplicationBarIconButton).IsEnabled = true;
                (ApplicationBar.MenuItems[0] as ApplicationBarMenuItem).IsEnabled = true;
                (ApplicationBar.MenuItems[1] as ApplicationBarMenuItem).IsEnabled = true;
                (ApplicationBar.MenuItems[2] as ApplicationBarMenuItem).IsEnabled = true;
                (ApplicationBar.MenuItems[3] as ApplicationBarMenuItem).IsEnabled = true;
                textBlock1.Visibility = System.Windows.Visibility.Visible;
                textBox1.Visibility   = System.Windows.Visibility.Visible;
            }
        }
 private void Open_Click(object sender, EventArgs e)
 {
     using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
     {
         if (storage.FileExists(@"customphoto.jpg"))
         {
             using (IsolatedStorageFileStream stream =
                        storage.OpenFile(@"customphoto.jpg", FileMode.Open))
             {
                 currentImage        = PictureDecoder.DecodeJpeg(stream);
                 photoContainer.Fill = new ImageBrush {
                     ImageSource = currentImage
                 };
             }
             imageDetails.Text = string.Format("Image loaded from filename:\ncustomphoto.jpg");
         }
         else
         {
             photoContainer.Fill = new SolidColorBrush(Colors.Gray);
             imageDetails.Text   = "Image not found!";
         }
     }
 }
        void OpenFromLibrary_Click(object sender, EventArgs e)
        {
            var library  = new MediaLibrary();
            var pictures = library.SavedPictures;
            var picture  = pictures.FirstOrDefault(item => item.Name == "customphoto.jpg");

            if (picture != null)
            {
                using (var stream = picture.GetImage())
                {
                    currentImage = PictureDecoder.DecodeJpeg(stream);
                }
                photoContainer.Fill = new ImageBrush {
                    ImageSource = currentImage
                };
                imageDetails.Text = string.Format("Image from Album: {0}\nPicture name: {1}", picture.Album, picture.GetPath());
            }
            else
            {
                photoContainer.Fill = new SolidColorBrush(Colors.Gray);
                imageDetails.Text   = "Choose an image source from the menu.";
            }
        }
Beispiel #21
0
        //

#if WINDOWS_PHONE
        public static byte[] ResizeImageWinPhone(byte[] imageData, float width, float height)
        {
            byte[] resizedData;


            using (MemoryStream streamIn = new MemoryStream(imageData))
            {
                WriteableBitmap bitmap = PictureDecoder.DecodeJpeg(streamIn, (int)width, (int)height);
                //
                float ZielHoehe  = 0;
                float ZielBreite = 0;
                //
                float Hoehe  = bitmap.PixelHeight;
                float Breite = bitmap.PixelWidth;
                //
                if (Hoehe > Breite) // Höhe (71 für Avatar) ist Master
                {
                    ZielHoehe = height;
                    float teiler = Hoehe / height;
                    ZielBreite = Breite / teiler;
                }
                else // Breite (61 für Avatar) ist Master
                {
                    ZielBreite = width;
                    float teiler = Breite / width;
                    ZielHoehe = Hoehe / teiler;
                }
                //
                using (MemoryStream streamOut = new MemoryStream())
                {
                    bitmap.SaveJpeg(streamOut, (int)ZielBreite, (int)ZielHoehe, 0, 100);
                    resizedData = streamOut.ToArray();
                }
            }
            return(resizedData);
        }
        public void onCameraTaskCompleted(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)
                    {
                        // Save image in media library
                        if (cameraOptions.SaveToPhotoAlbum)
                        {
                            MediaLibrary library = new MediaLibrary();
                            Picture      pict    = library.SavePicture(e.OriginalFileName, e.ChosenPhoto); // to save to photo-roll ...
                        }

                        int orient   = ImageExifHelper.getImageOrientationFromStream(e.ChosenPhoto);
                        int newAngle = 0;
                        switch (orient)
                        {
                        case ImageExifOrientation.LandscapeLeft:
                            newAngle = 90;
                            break;

                        case ImageExifOrientation.PortraitUpsideDown:
                            newAngle = 180;
                            break;

                        case ImageExifOrientation.LandscapeRight:
                            newAngle = 270;
                            break;

                        case ImageExifOrientation.Portrait:
                        default: break;         // 0 default already set
                        }

                        Stream rotImageStream = ImageExifHelper.RotateStream(e.ChosenPhoto, newAngle);

                        // we should return stream position back after saving stream to media library
                        rotImageStream.Seek(0, SeekOrigin.Begin);

                        WriteableBitmap image = PictureDecoder.DecodeJpeg(rotImageStream);

                        imagePathOrContent = this.SaveImageToLocalStorage(image, Path.GetFileName(e.OriginalFileName));
                    }
                    else if (cameraOptions.DestinationType == DATA_URL)
                    {
                        imagePathOrContent = this.GetImageContent(e.ChosenPhoto);
                    }
                    else
                    {
                        // TODO: shouldn't this happen before we launch the camera-picker?
                        DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Incorrect option: destinationType"));
                        return;
                    }

                    DispatchCommandResult(new PluginResult(PluginResult.Status.OK, imagePathOrContent));
                }
                catch (Exception)
                {
                    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;
            }
        }
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var timer = Stopwatch.StartNew();

            var encryptedPhoto = value as TLEncryptedFile;

            if (encryptedPhoto != null)
            {
                return(ReturnOrEnqueueImage(timer, encryptedPhoto, encryptedPhoto));
            }

            var userProfilePhoto = value as TLUserProfilePhoto;

            if (userProfilePhoto != null)
            {
                var location = userProfilePhoto.PhotoSmall as TLFileLocation;
                if (location != null)
                {
                    return(ReturnOrEnqueueProfileImage(timer, location, userProfilePhoto, new TLInt(0)));
                }
            }

            var chatPhoto = value as TLChatPhoto;

            if (chatPhoto != null)
            {
                var location = chatPhoto.PhotoSmall as TLFileLocation;
                if (location != null)
                {
                    return(ReturnOrEnqueueProfileImage(timer, location, chatPhoto, new TLInt(0)));
                }
            }

            var decrypteMedia = value as TLDecryptedMessageMediaBase;

            if (decrypteMedia != null)
            {
                var decryptedMediaVideo = value as TLDecryptedMessageMediaVideo;
                if (decryptedMediaVideo != null)
                {
                    var buffer = decryptedMediaVideo.Thumb.Data;

                    if (buffer.Length > 0 &&
                        decryptedMediaVideo.ThumbW.Value > 0 &&
                        decryptedMediaVideo.ThumbH.Value > 0)
                    {
                        var memoryStream = new MemoryStream(buffer);
                        var bitmap       = PictureDecoder.DecodeJpeg(memoryStream);

                        bitmap.BoxBlur(37);

                        var blurredStream = new MemoryStream();
                        bitmap.SaveJpeg(blurredStream, decryptedMediaVideo.ThumbW.Value, decryptedMediaVideo.ThumbH.Value, 0, 70);

                        return(ImageUtils.CreateImage(blurredStream.ToArray()));
                    }

                    return(ImageUtils.CreateImage(buffer));
                }

                var decryptedMediaDocument = value as TLDecryptedMessageMediaDocument;
                if (decryptedMediaDocument != null)
                {
                    var location = decryptedMediaDocument.File as TLEncryptedFile;
                    if (location != null)
                    {
                        var fileName = String.Format("{0}_{1}_{2}.jpg",
                                                     location.Id,
                                                     location.DCId,
                                                     location.AccessHash);

                        using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            if (store.FileExists(fileName))
                            {
                                BitmapImage imageSource;

                                try
                                {
                                    using (var stream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                                    {
                                        stream.Seek(0, SeekOrigin.Begin);
                                        var image = new BitmapImage();
                                        image.SetSource(stream);
                                        imageSource = image;
                                    }
                                }
                                catch (Exception)
                                {
                                    return(null);
                                }

                                return(imageSource);
                            }
                        }
                    }

                    var buffer = decryptedMediaDocument.Thumb.Data;
                    return(ImageUtils.CreateImage(buffer));
                }

                var file = decrypteMedia.File as TLEncryptedFile;
                if (file != null)
                {
                    return(ReturnOrEnqueueImage(timer, file, decrypteMedia));
                }
            }

            var decryptedMessage = value as TLDecryptedMessage17;

            if (decryptedMessage != null)
            {
                var decryptedMediaExternalDocument = decryptedMessage.Media as TLDecryptedMessageMediaExternalDocument;
                if (decryptedMediaExternalDocument != null)
                {
#if WP8
                    return(ReturnOrEnqueueSticker(decryptedMediaExternalDocument, decryptedMessage));
#endif

                    return(null);
                }
            }

            var photoMedia = value as TLMessageMediaPhoto;
            if (photoMedia != null)
            {
                value = photoMedia.Photo;
            }

            var photo = value as TLPhoto;
            if (photo != null)
            {
                var    width = 311.0;
                double result;
                if (Double.TryParse((string)parameter, out result))
                {
                    width = result;
                }

                TLPhotoSize size  = null;
                var         sizes = photo.Sizes.OfType <TLPhotoSize>();
                foreach (var photoSize in sizes)
                {
                    if (size == null ||
                        Math.Abs(width - size.W.Value) > Math.Abs(width - photoSize.W.Value))
                    {
                        size = photoSize;
                    }
                }

                if (size != null)
                {
                    var location = size.Location as TLFileLocation;
                    if (location != null)
                    {
                        return(ReturnOrEnqueueImage(timer, location, photo, size.Size));
                    }
                }
            }

#if WP8
            var sticker = value as TLStickerItem;
            if (sticker != null)
            {
                var document22 = sticker.Document as TLDocument22;
                if (document22 == null)
                {
                    return(null);
                }

                var thumbCachedSize = document22.Thumb as TLPhotoCachedSize;
                if (thumbCachedSize != null)
                {
                    var fileName = "cached" + document22.GetFileName();
                    var buffer   = thumbCachedSize.Bytes.Data;
                    if (buffer == null)
                    {
                        return(null);
                    }

                    return(DecodeWebPImage(fileName, buffer, () => { }));
                }

                var thumbPhotoSize = document22.Thumb as TLPhotoSize;
                if (thumbPhotoSize != null)
                {
                    var location = thumbPhotoSize.Location as TLFileLocation;
                    if (location != null)
                    {
                        return(ReturnOrEnqueueStickerPreview(location, sticker, thumbPhotoSize.Size));
                    }
                }

                if (TLMessageBase.IsSticker(document22))
                {
                    return(ReturnOrEnqueueSticker(document22, sticker));
                }
            }
#endif

            var document = value as TLDocument;
            if (document != null)
            {
#if WP8
                if (TLMessageBase.IsSticker(document))
                {
                    if (parameter != null &&
                        string.Equals(parameter.ToString(), "ignoreStickers", StringComparison.OrdinalIgnoreCase))
                    {
                        return(null);
                    }

                    return(ReturnOrEnqueueSticker((TLDocument22)document, null));
                }
#endif

                var thumbPhotoSize = document.Thumb as TLPhotoSize;
                if (thumbPhotoSize != null)
                {
                    var location = thumbPhotoSize.Location as TLFileLocation;
                    if (location != null)
                    {
                        return(ReturnOrEnqueueImage(timer, location, document, thumbPhotoSize.Size));
                    }
                }

                var thumbCachedSize = document.Thumb as TLPhotoCachedSize;
                if (thumbCachedSize != null)
                {
                    var buffer = thumbCachedSize.Bytes.Data;

                    return(ImageUtils.CreateImage(buffer));
                }
            }

            var videoMedia = value as TLMessageMediaVideo;
            if (videoMedia != null)
            {
                value = videoMedia.Video;
            }

            var video = value as TLVideo;
            if (video != null)
            {
                var thumbPhotoSize = video.Thumb as TLPhotoSize;

                if (thumbPhotoSize != null)
                {
                    var location = thumbPhotoSize.Location as TLFileLocation;
                    if (location != null)
                    {
                        return(ReturnOrEnqueueImage(timer, location, video, thumbPhotoSize.Size));
                    }
                }

                var thumbCachedSize = video.Thumb as TLPhotoCachedSize;
                if (thumbCachedSize != null)
                {
                    var buffer = thumbCachedSize.Bytes.Data;
                    return(ImageUtils.CreateImage(buffer));
                }
            }

            var webPageMedia = value as TLMessageMediaWebPage;
            if (webPageMedia != null)
            {
                value = webPageMedia.WebPage;
            }

            var webPage = value as TLWebPage;
            if (webPage != null)
            {
                var webPagePhoto = webPage.Photo as TLPhoto;
                if (webPagePhoto != null)
                {
                    var    width = 311.0;
                    double result;
                    if (Double.TryParse((string)parameter, out result))
                    {
                        width = result;
                    }

                    TLPhotoSize size  = null;
                    var         sizes = webPagePhoto.Sizes.OfType <TLPhotoSize>();
                    foreach (var photoSize in sizes)
                    {
                        if (size == null ||
                            Math.Abs(width - size.W.Value) > Math.Abs(width - photoSize.W.Value))
                        {
                            size = photoSize;
                        }
                    }

                    if (size != null)
                    {
                        var location = size.Location as TLFileLocation;
                        if (location != null)
                        {
                            return(ReturnOrEnqueueImage(timer, location, webPage, size.Size));
                        }
                    }
                }
            }

            return(null);
        }
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var isBlurEnabled = parameter == null || !string.Equals(parameter.ToString(), "noblur", StringComparison.OrdinalIgnoreCase);

            var options = BitmapCreateOptions.DelayCreation | BitmapCreateOptions.BackgroundCreation;

            var decryptedMediaPhoto = value as TLDecryptedMessageThumbMediaBase;

            if (decryptedMediaPhoto != null)
            {
                var buffer = decryptedMediaPhoto.Thumb.Data;

                if (buffer.Length > 0 &&
                    decryptedMediaPhoto.ThumbW.Value > 0 &&
                    decryptedMediaPhoto.ThumbH.Value > 0)
                {
                    if (!isBlurEnabled)
                    {
                        return(ImageUtils.CreateImage(buffer, options));
                    }
                    else
                    {
                        try
                        {
                            var memoryStream = new MemoryStream(buffer);
                            var bitmap       = PictureDecoder.DecodeJpeg(memoryStream);

                            BlurBitmap(bitmap, Secret);

                            var blurredStream = new MemoryStream();
                            bitmap.SaveJpeg(blurredStream, decryptedMediaPhoto.ThumbW.Value, decryptedMediaPhoto.ThumbH.Value, 0, 100);

                            return(ImageUtils.CreateImage(blurredStream, options));
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                }

                return(null);
            }

            var mediaDocument = value as TLMessageMediaDocument;

            if (mediaDocument != null)
            {
                var document = mediaDocument.Document as TLDocument;
                if (document != null)
                {
                    var size = document.Thumb as TLPhotoSize;
                    if (size != null)
                    {
                        if (!string.IsNullOrEmpty(size.TempUrl))
                        {
                            return(size.TempUrl);
                        }

                        var location = size.Location as TLFileLocation;
                        if (location != null)
                        {
                            var fileName = String.Format("{0}_{1}_{2}.jpg",
                                                         location.VolumeId,
                                                         location.LocalId,
                                                         location.Secret);

                            if (!isBlurEnabled)
                            {
                                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                                {
                                    if (store.FileExists(fileName))
                                    {
                                        try
                                        {
                                            using (var stream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                                            {
                                                return(ImageUtils.CreateImage(stream, options));
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                        }
                                    }
                                    else
                                    {
                                        var fileManager = IoC.Get <IFileManager>();
                                        fileManager.DownloadFile(location, document, size.Size,
                                                                 item =>
                                        {
                                            mediaDocument.NotifyOfPropertyChange(() => mediaDocument.ThumbSelf);
                                        });
                                    }
                                }
                            }
                            else
                            {
                                BitmapImage preview;
                                if (TryGetDocumentPreview(document.Id, out preview, options))
                                {
                                    return(preview);
                                }

                                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                                {
                                    if (store.FileExists(fileName))
                                    {
                                        try
                                        {
                                            using (var stream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                                            {
                                                var bitmap = PictureDecoder.DecodeJpeg(stream);

                                                BlurBitmap(bitmap, Secret);

                                                var blurredStream = new MemoryStream();
                                                bitmap.SaveJpeg(blurredStream, size.W.Value, size.H.Value, 0, 100);

                                                return(bitmap);
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                        }
                                    }
                                }

                                var fileManager = IoC.Get <IFileManager>();
                                fileManager.DownloadFile(location, document, size.Size,
                                                         item =>
                                {
                                    Execute.BeginOnUIThread(() =>
                                    {
                                        using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                                        {
                                            if (store.FileExists(fileName))
                                            {
                                                try
                                                {
                                                    using (var stream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                                                    {
                                                        var bitmap = PictureDecoder.DecodeJpeg(stream);

                                                        BlurBitmap(bitmap, Secret);

                                                        var blurredStream = new MemoryStream();
                                                        bitmap.SaveJpeg(blurredStream, size.W.Value, size.H.Value, 0, 100);

                                                        var previewfileName = string.Format("preview_document{0}.jpg", document.Id);
                                                        SaveFile(previewfileName, blurredStream);

                                                        mediaDocument.NotifyOfPropertyChange(() => mediaDocument.ThumbSelf);
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                }
                                            }
                                        }
                                    });
                                });
                            }
                        }
                    }

                    var cachedSize = document.Thumb as TLPhotoCachedSize;
                    if (cachedSize != null)
                    {
                        if (!string.IsNullOrEmpty(cachedSize.TempUrl))
                        {
                            return(cachedSize.TempUrl);
                        }

                        var buffer = cachedSize.Bytes.Data;

                        if (buffer != null && buffer.Length > 0)
                        {
                            if (!isBlurEnabled)
                            {
                                return(ImageUtils.CreateImage(buffer, options));
                            }
                            else
                            {
                                BitmapImage preview;
                                if (TryGetDocumentPreview(document.Id, out preview, options))
                                {
                                    return(preview);
                                }

                                try
                                {
                                    var bitmap = PictureDecoder.DecodeJpeg(new MemoryStream(buffer));

                                    BlurBitmap(bitmap, Secret);

                                    var blurredStream = new MemoryStream();
                                    bitmap.SaveJpeg(blurredStream, cachedSize.W.Value, cachedSize.H.Value, 0, 100);

                                    var fileName = string.Format("preview_document{0}.jpg", document.Id);

                                    Telegram.Api.Helpers.Execute.BeginOnThreadPool(() => SaveFile(fileName, blurredStream));

                                    return(ImageUtils.CreateImage(blurredStream, options));
                                }
                                catch (Exception ex)
                                {
                                }
                            }
                        }

                        return(null);
                    }

                    return(null);
                }
            }

            var mediaPhoto = value as TLMessageMediaPhoto;

            if (mediaPhoto != null)
            {
                var photo = mediaPhoto.Photo as TLPhoto;
                if (photo != null)
                {
                    var size = photo.Sizes.FirstOrDefault(x => TLString.Equals(x.Type, new TLString("s"), StringComparison.OrdinalIgnoreCase)) as TLPhotoSize;
                    if (size != null)
                    {
                        if (!string.IsNullOrEmpty(size.TempUrl))
                        {
                            return(size.TempUrl);
                        }

                        var location = size.Location as TLFileLocation;
                        if (location != null)
                        {
                            var fileName = String.Format("{0}_{1}_{2}.jpg",
                                                         location.VolumeId,
                                                         location.LocalId,
                                                         location.Secret);

                            if (!isBlurEnabled)
                            {
                                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                                {
                                    if (store.FileExists(fileName))
                                    {
                                        try
                                        {
                                            using (var stream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                                            {
                                                return(ImageUtils.CreateImage(stream, options));
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                        }
                                    }
                                    else
                                    {
                                        var fileManager = IoC.Get <IFileManager>();
                                        fileManager.DownloadFile(location, photo, size.Size,
                                                                 item =>
                                        {
                                            mediaPhoto.NotifyOfPropertyChange(() => mediaPhoto.ThumbSelf);
                                        });
                                    }
                                }
                            }
                            else
                            {
                                BitmapImage preview;
                                if (TryGetPhotoPreview(photo.Id, out preview, options))
                                {
                                    return(preview);
                                }

                                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                                {
                                    if (store.FileExists(fileName))
                                    {
                                        try
                                        {
                                            using (var stream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                                            {
                                                var bitmap = PictureDecoder.DecodeJpeg(stream);

                                                BlurBitmap(bitmap, Secret);

                                                var blurredStream = new MemoryStream();
                                                bitmap.SaveJpeg(blurredStream, size.W.Value, size.H.Value, 0, 100);

                                                return(bitmap);
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                        }
                                    }
                                }

                                if (location.DCId.Value == 0)
                                {
                                    return(null);
                                }

                                var fileManager = IoC.Get <IFileManager>();
                                fileManager.DownloadFile(location, photo, size.Size,
                                                         item =>
                                {
                                    Execute.BeginOnUIThread(() =>
                                    {
                                        using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                                        {
                                            if (store.FileExists(fileName))
                                            {
                                                try
                                                {
                                                    using (var stream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                                                    {
                                                        var bitmap = PictureDecoder.DecodeJpeg(stream);

                                                        BlurBitmap(bitmap, Secret);

                                                        var blurredStream = new MemoryStream();
                                                        bitmap.SaveJpeg(blurredStream, size.W.Value, size.H.Value, 0, 100);

                                                        var previewfileName = string.Format("preview{0}.jpg", photo.Id);
                                                        SaveFile(previewfileName, blurredStream);

                                                        mediaPhoto.NotifyOfPropertyChange(() => mediaPhoto.ThumbSelf);
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                }
                                            }
                                        }
                                    });
                                });
                            }
                        }
                    }

                    var cachedSize = (TLPhotoCachedSize)photo.Sizes.FirstOrDefault(x => x is TLPhotoCachedSize);
                    if (cachedSize != null)
                    {
                        if (!string.IsNullOrEmpty(cachedSize.TempUrl))
                        {
                            return(cachedSize.TempUrl);
                        }

                        var buffer = cachedSize.Bytes.Data;

                        if (buffer != null && buffer.Length > 0)
                        {
                            if (!isBlurEnabled)
                            {
                                return(ImageUtils.CreateImage(buffer, options));
                            }
                            else
                            {
                                BitmapImage preview;
                                if (TryGetPhotoPreview(photo.Id, out preview, options))
                                {
                                    return(preview);
                                }

                                try
                                {
                                    var bitmap = PictureDecoder.DecodeJpeg(new MemoryStream(buffer));

                                    BlurBitmap(bitmap, Secret);

                                    var blurredStream = new MemoryStream();
                                    bitmap.SaveJpeg(blurredStream, cachedSize.W.Value, cachedSize.H.Value, 0, 100);

                                    var fileName = string.Format("preview{0}.jpg", photo.Id);

                                    Telegram.Api.Helpers.Execute.BeginOnThreadPool(() => SaveFile(fileName, blurredStream));

                                    return(ImageUtils.CreateImage(blurredStream, options));
                                }
                                catch (Exception ex)
                                {
                                }
                            }
                        }

                        return(null);
                    }

                    return(null);
                }
            }

            var mediaGame = value as TLMessageMediaGame;

            if (mediaGame != null)
            {
                var photo = mediaGame.Photo as TLPhoto;
                if (photo != null)
                {
                    var size = photo.Sizes.FirstOrDefault(x => TLString.Equals(x.Type, new TLString("s"), StringComparison.OrdinalIgnoreCase)) as TLPhotoSize;
                    if (size != null)
                    {
                        if (!string.IsNullOrEmpty(size.TempUrl))
                        {
                            return(size.TempUrl);
                        }

                        var location = size.Location as TLFileLocation;
                        if (location != null)
                        {
                            var fileName = String.Format("{0}_{1}_{2}.jpg",
                                                         location.VolumeId,
                                                         location.LocalId,
                                                         location.Secret);

                            if (!isBlurEnabled)
                            {
                                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                                {
                                    if (store.FileExists(fileName))
                                    {
                                        try
                                        {
                                            using (var stream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                                            {
                                                return(ImageUtils.CreateImage(stream, options));
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                        }
                                    }
                                    else
                                    {
                                        var fileManager = IoC.Get <IFileManager>();
                                        fileManager.DownloadFile(location, photo, size.Size,
                                                                 item =>
                                        {
                                            mediaGame.NotifyOfPropertyChange(() => mediaGame.ThumbSelf);
                                        });
                                    }
                                }
                            }
                            else
                            {
                                BitmapImage preview;
                                if (TryGetPhotoPreview(photo.Id, out preview, options))
                                {
                                    return(preview);
                                }

                                var fileManager = IoC.Get <IFileManager>();
                                fileManager.DownloadFile(location, photo, size.Size,
                                                         item =>
                                {
                                    Execute.BeginOnUIThread(() =>
                                    {
                                        using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                                        {
                                            if (store.FileExists(fileName))
                                            {
                                                try
                                                {
                                                    using (var stream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                                                    {
                                                        var bitmap = PictureDecoder.DecodeJpeg(stream);

                                                        BlurBitmap(bitmap, Secret);

                                                        var blurredStream = new MemoryStream();
                                                        bitmap.SaveJpeg(blurredStream, size.W.Value, size.H.Value, 0, 100);

                                                        var previewfileName = string.Format("preview{0}.jpg", photo.Id);
                                                        SaveFile(previewfileName, blurredStream);

                                                        mediaGame.NotifyOfPropertyChange(() => mediaGame.ThumbSelf);
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                }
                                            }
                                        }
                                    });
                                });
                            }
                        }
                    }

                    var cachedSize = (TLPhotoCachedSize)photo.Sizes.FirstOrDefault(x => x is TLPhotoCachedSize);
                    if (cachedSize != null)
                    {
                        if (!string.IsNullOrEmpty(cachedSize.TempUrl))
                        {
                            return(cachedSize.TempUrl);
                        }

                        var buffer = cachedSize.Bytes.Data;

                        if (buffer != null && buffer.Length > 0)
                        {
                            if (!isBlurEnabled)
                            {
                                return(ImageUtils.CreateImage(buffer, options));
                            }
                            else
                            {
                                BitmapImage preview;
                                if (TryGetPhotoPreview(photo.Id, out preview, options))
                                {
                                    return(preview);
                                }

                                try
                                {
                                    var bitmap = PictureDecoder.DecodeJpeg(new MemoryStream(buffer));

                                    BlurBitmap(bitmap, Secret);

                                    var blurredStream = new MemoryStream();
                                    bitmap.SaveJpeg(blurredStream, cachedSize.W.Value, cachedSize.H.Value, 0, 100);

                                    var fileName = string.Format("preview{0}.jpg", photo.Id);

                                    Telegram.Api.Helpers.Execute.BeginOnThreadPool(() => SaveFile(fileName, blurredStream));

                                    return(ImageUtils.CreateImage(blurredStream));
                                }
                                catch (Exception ex)
                                {
                                }
                            }
                        }

                        return(null);
                    }

                    return(null);
                }
            }

            return(null);
        }
Beispiel #25
0
        public WriteableBitmap ReadOriginalImage(string albumId = "", int seqNo = -1)
        {
            string str  = this._albumId;
            int    num1 = this._seqNo;

            if (albumId != "" && seqNo != -1)
            {
                str  = albumId;
                num1 = seqNo;
            }
            if (this._originalImage != null && this._orImAlbumId == str && this._orImSeqNo == num1)
            {
                return(this._originalImage.Clone());
            }
            Stopwatch stopwatch    = Stopwatch.StartNew();
            Picture   galleryImage = this.GetGalleryImage(str, num1);
            int       num2         = galleryImage.Width;
            int       num3         = galleryImage.Height;

            if (!MemoryInfo.IsLowMemDevice)
            {
                int num4 = galleryImage.Width * galleryImage.Height;
                if (num4 > VKConstants.ResizedImageSize)
                {
                    double num5 = Math.Sqrt((double)num4 / (double)VKConstants.ResizedImageSize);
                    num2 = (int)Math.Round((double)galleryImage.Width / num5);
                    num3 = (int)Math.Round((double)galleryImage.Height / num5);
                }
            }
            else
            {
                double num4         = 0.0;
                double num5         = 0.0;
                Size   viewportSize = this.ViewportSize;
                // ISSUE: explicit reference operation
                double width = ((Size)@viewportSize).Width;
                viewportSize = this.ViewportSize;
                // ISSUE: explicit reference operation
                double height = ((Size)@viewportSize).Height;
                Rect   fit    = RectangleUtils.ResizeToFit(new Rect(num4, num5, width, height), new Size((double)galleryImage.Width, (double)galleryImage.Height));
                double num6   = 300.0;
                // ISSUE: explicit reference operation
                // ISSUE: explicit reference operation
                double num7 = Math.Min(((Rect)@fit).Width, ((Rect)@fit).Height);
                double num8 = 1.0;
                if (num7 < num6)
                {
                    num8 = num6 / num7;
                }
                // ISSUE: explicit reference operation
                num2 = (int)(((Rect)@fit).Width * num8);
                // ISSUE: explicit reference operation
                num3 = (int)(((Rect)@fit).Height * num8);
            }
            WriteableBitmap wb  = PictureDecoder.DecodeJpeg(galleryImage.GetImage(), num2, num3);
            WriteableBitmap bmp = this.RotateIfNeeded(str, num1, wb);

            if (albumId == "")
            {
                this._originalImage = bmp.Clone();
                this._orImAlbumId   = str;
                this._orImSeqNo     = num1;
            }
            stopwatch.Stop();
            galleryImage.Dispose();
            return(bmp);
        }
Beispiel #26
0
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var decryptedMediaPhoto = value as TLDecryptedMessageThumbMediaBase;

            if (decryptedMediaPhoto != null)
            {
                var buffer = decryptedMediaPhoto.Thumb.Data;

                if (buffer.Length > 0 &&
                    decryptedMediaPhoto.ThumbW.Value > 0 &&
                    decryptedMediaPhoto.ThumbH.Value > 0)
                {
                    var memoryStream = new MemoryStream(buffer);
                    var bitmap       = PictureDecoder.DecodeJpeg(memoryStream);

                    bitmap.BoxBlur(37);

                    var blurredStream = new MemoryStream();
                    bitmap.SaveJpeg(blurredStream, decryptedMediaPhoto.ThumbW.Value, decryptedMediaPhoto.ThumbH.Value, 0, 70);

                    return(ImageUtils.CreateImage(blurredStream.ToArray()));
                }

                return(null);
            }

            var mediaPhoto = value as TLMessageMediaPhoto;

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

            var photo = mediaPhoto.Photo as TLPhoto;

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

            var cachedSize = (TLPhotoCachedSize)photo.Sizes.FirstOrDefault(x => x is TLPhotoCachedSize);

            if (cachedSize != null)
            {
                var buffer = cachedSize.Bytes.Data;

                //return ImageUtils.CreateImage(buffer);

                if (buffer != null && buffer.Length > 0)
                {
                    var fileName = string.Format("preview{0}.jpg", photo.Id);
                    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (store.FileExists(fileName))
                        {
                            BitmapImage imageSource;

                            try
                            {
                                using (var stream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                                {
                                    stream.Seek(0, SeekOrigin.Begin);
                                    var image = new BitmapImage();
                                    image.SetSource(stream);
                                    imageSource = image;
                                }
                            }
                            catch (Exception)
                            {
                                return(null);
                            }

                            return(imageSource);
                        }
                    }

                    var memoryStream = new MemoryStream(buffer);
                    var bitmap       = PictureDecoder.DecodeJpeg(memoryStream);

                    bitmap.BoxBlur(7);

                    var blurredStream = new MemoryStream();
                    bitmap.SaveJpeg(blurredStream, cachedSize.W.Value, cachedSize.H.Value, 0, 70);

                    Telegram.Api.Helpers.Execute.BeginOnThreadPool(() =>
                    {
                        using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            try
                            {
                                using (var stream = store.OpenFile(fileName, FileMode.OpenOrCreate, FileAccess.Write))
                                {
                                    buffer = blurredStream.ToArray();
                                    stream.Seek(0, SeekOrigin.Begin);
                                    stream.Write(buffer, 0, buffer.Length);
                                }
                            }
                            catch (Exception)
                            {
                            }
                        }
                    });

                    return(ImageUtils.CreateImage(blurredStream.ToArray()));
                }

                return(null);
            }

            return(null);
        }
        void generationWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            int index = (int)e.Argument;

            DateTime now       = DateTime.Now;
            string   photoName = String.Format("daily_{0}.jpg", now.Ticks);

            Dispatcher.BeginInvoke(() =>
            {
                using (MemoryStream stream = new MemoryStream())
                {
                    Stream bgStream = Application.GetResourceStream(new Uri(String.Format("Assets/CalendarTemplate/{0}.jpg", index), UriKind.Relative)).Stream;
                    var container   = new StackPanel()
                    {
                        Width      = Constant.GENERATED_IMAGE_WIDTH,
                        Height     = Constant.GENERATED_IMAGE_HEIGHT,
                        Background = new ImageBrush()
                        {
                            ImageSource = PictureDecoder.DecodeJpeg(bgStream, Constant.GENERATED_IMAGE_WIDTH, Constant.GENERATED_IMAGE_HEIGHT)
                        }
                    };
                    bgStream.Close();

                    var marginLeft = 20;
                    var marginTop  = 50;
                    var offset     = 25;

                    var imageContainer = new Canvas()
                    {
                        Width               = Constant.GENERATED_CALENDAR_WIDTH + offset * 2,
                        Height              = Constant.GENERATED_IMAGE_HEIGHT,
                        Background          = new SolidColorBrush(Colors.Transparent),
                        Margin              = new Thickness(marginLeft, 0, 0, 0),
                        HorizontalAlignment = HorizontalAlignment.Left
                    };

                    var opacityBorder = new Border()
                    {
                        Width      = Constant.GENERATED_CALENDAR_WIDTH + offset * 2,
                        Height     = Constant.GENERATED_IMAGE_HEIGHT,
                        Background = new SolidColorBrush(Colors.Black),
                        Opacity    = 0.5
                    };

                    var calendar = new CalendarForRender()
                    {
                        DataContext = App.ViewModelData,
                        Width       = Constant.GENERATED_CALENDAR_WIDTH,
                        Margin      = new Thickness(offset, marginTop, 0, 0)
                    };
                    //calendar.Calendar.SelectedDate = DateTime.Now;
                    calendar.Calendar.SelectedMonth = DateSelector.SelectedValue.Month;
                    calendar.Calendar.SelectedYear  = DateSelector.SelectedValue.Year;
                    calendar.Calendar.Refresh();

                    imageContainer.Children.Add(opacityBorder);
                    imageContainer.Children.Add(calendar);

                    container.Children.Add(imageContainer);
                    container.Measure(new Size(Constant.GENERATED_IMAGE_WIDTH, Constant.GENERATED_IMAGE_HEIGHT));
                    container.Arrange(new Rect(0, 0, Constant.GENERATED_IMAGE_WIDTH, Constant.GENERATED_IMAGE_HEIGHT));

                    var bitmap = new WriteableBitmap(container, null);
                    bitmap.SaveJpeg(stream, bitmap.PixelWidth, bitmap.PixelHeight, 0, 100);
                    stream.Seek(0, SeekOrigin.Begin);
                    using (MediaLibrary library = new MediaLibrary())
                    {
                        library.SavePicture(photoName, stream);
                    }
                }
            });
        }