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

                MediaLibrary library = new MediaLibrary();
                library.SavePictureToCameraRoll("CameraExplorer_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".jpg", _dataContext.ImageStream);

                // There should be no temporary file left behind
                using (var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    var files = isolatedStorage.GetFileNames("CameraExplorer_*.jpg");
                    foreach (string file in files)
                    {
                        isolatedStorage.DeleteFile(file);
                        //System.Diagnostics.Debug.WriteLine("Temp file deleted: " + file);
                    }
                }

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

            NavigationService.GoBack();
        }
 public void PlayAlbumArtist(MediaLibrary.AlbumArtist artist, bool enqueue,
     Action<MediaState, object, Exception> callback, object state)
 {
     lock (_syncLock)
     {
         Tuple<Action<MediaState, object, Exception>, object> innerState = new Tuple<Action<MediaState, object, Exception>, object>(callback, state);
         QueueRequest(new PlayAlbumArtistDelegate(PlaybackServiceClient.PlayAlbumArtistAsync), new PlayAlbumArtistRequest(artist.ConvertToArtist(), enqueue), innerState);
     }
 }
 public void GetAlbumArtByTrackAsync(MediaLibrary.Track track,
     Action<MediaLibrary.Track, byte[], object, Exception> callback, object state)
 {
     lock (_syncLock)
     {
         Tuple<Action<MediaLibrary.Track, byte[], object, Exception>, object, MediaLibrary.Track> innerState =
             new Tuple<Action<MediaLibrary.Track, byte[], object, Exception>, object, MediaLibrary.Track>(callback, state, track);
         QueueLowPriorityRequest(new GetAlbumArtByTrackDelegate(LibraryServiceClient.GetAlbumArtByTrackAsync), new GetAlbumArtByTrackRequest(track), innerState);
     }
 }
 public void GetAlbumArtByAlbumAsync(MediaLibrary.Album album,
     Action<MediaLibrary.Album, byte[], object, Exception> callback, object state)
 {
     lock (_syncLock)
     {
         Tuple<Action<MediaLibrary.Album, byte[], object, Exception>, object, MediaLibrary.Album> innerState =
             new Tuple<Action<MediaLibrary.Album, byte[], object, Exception>, object, MediaLibrary.Album>(callback, state, album);
         QueueLowPriorityRequest(new GetAlbumArtByAlbumDelegate(LibraryServiceClient.GetAlbumArtByAlbumAsync), new GetAlbumArtByAlbumRequest(album), innerState);
     }
 }
Esempio n. 5
0
        public static bool EqualsTrack(this MediaLibrary.Track track, MediaLibrary.Track track2)
        {
            if (track == null && track2 == null)
            {
                return true;
            }
            else if (track == null || track2 == null)
            {
                return false;
            }

            return (track.FilePath == track2.FilePath);
        }
Esempio n. 6
0
 public void CancelRequest(MediaLibrary.Album album)
 {
     if (_queuedRequests.Contains(album))
     {
         lock (_requestLock)
         {
             if (_queuedRequests.Contains(album))
             {
                 Debug.WriteLine("Cancelled request for {0}", album.ID);
                 _queuedRequests.Remove(album);
             }
         }
     }
 }
Esempio n. 7
0
 public MixerRoom(IGame game) : base(game, ROOM_ID)
 {
     _mlib         = new MediaLibrary();
     _mixer        = new AudioMixer(4);
     _channelInfos = new List <ILabel>();
 }
Esempio n. 8
0
        public async Task GetPhotos()
        {
            try
            {
                List <Photo> imageList = new List <Photo>();
                if (App.SaveToCameraRollEnabled)
                {
                    using (MediaLibrary library = new MediaLibrary())
                    {
                        foreach (PictureAlbum album in library.RootPictureAlbum.Albums)
                        {
                            if (album.Name == "Camera Roll")
                            {
                                var images = from r in album.Pictures where r.Name.StartsWith("mapi_thumb_")  select r;
                                foreach (var item in images)
                                {
                                    Photo imageData = new Photo();
                                    imageData.TimeStamp = item.Date;
                                    imageData.Title     = item.Name.Replace("mapi_thumb_", "");
                                    BitmapImage bi = new BitmapImage();
                                    using (var stream = item.GetImage())
                                    {
                                        bi.SetSource(stream);
                                    }
                                    imageData.ThumbBitmapImage = bi;
                                    imageData.File             = null;
                                    imageData.ThumbFile        = null;
                                    imageData.ImageSource      = null;
                                    imageList.Add(imageData);
                                }
                            }
                        }
                    }
                }
                else
                {
                    using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (!storage.DirectoryExists("shared\\transfers"))
                        {
                            m_photos = new ObservableCollection <Photo>();
                        }

                        var folder = await ApplicationData.Current.LocalFolder.GetFolderAsync("shared\\transfers");

                        var images = await folder.GetFilesAsync();

                        var imagesNoThumb = from r in images where !r.Name.StartsWith("thumb_") select r;
                        foreach (var item in imagesNoThumb)
                        {
                            Photo imageData = new Photo();
                            imageData.TimeStamp = item.DateCreated.DateTime;
                            imageData.Title     = item.Name;
                            imageData.File      = item;
                            imageData.ThumbFile = await folder.GetFileAsync("thumb_" + item.Name);

                            imageData.ImageSource = new BitmapImage(new Uri(imageData.ThumbFile.Path))
                            {
                                CreateOptions = BitmapCreateOptions.IgnoreImageCache
                            };
                            imageList.Add(imageData);
                        }
                    }
                }

                PhotoList = new ObservableCollection <Photo>(imageList);
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR: " + ex.Message);
                m_photos = null;
            }
        }
Esempio n. 9
0
        private void SaveButton_Click(object sender, EventArgs e)
        {
            if (this.editedBitmap != null)
            {
                if ((Application.Current as App).TrialMode)
                {
                    MessageBoxResult result = MessageBoxResult.None;

                    try
                    {
                        result = MessageBox.Show(AppResources.MessageBoxMessageTrialVersionQuestion, AppResources.MessageBoxHeaderInfo, MessageBoxButton.OKCancel);
                    }
                    catch (Exception)
                    {
                        result = MessageBoxResult.None;
                    }

                    if (result == MessageBoxResult.OK)
                    {
                        try
                        {
                            this.marketplaceDetailTask.Show();
                        }
                        catch (Exception ex)
                        {
                            try
                            {
                                MessageBox.Show(AppResources.MessageBoxMessageMarketplaceOpenError + " " + ex.Message.ToString(), AppResources.MessageBoxHeaderError, MessageBoxButton.OK);
                            }
                            catch (Exception)
                            {
                                // Ignore
                            }
                        }
                    }
                }
                else
                {
                    try
                    {
                        using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            string file_name = "image.jpg";

                            if (store.FileExists(file_name))
                            {
                                store.DeleteFile(file_name);
                            }

                            using (IsolatedStorageFileStream stream = store.CreateFile(file_name))
                            {
                                this.editedBitmap.SaveJpeg(stream, this.editedBitmap.PixelWidth, this.editedBitmap.PixelHeight, 0, 100);
                            }

                            using (IsolatedStorageFileStream stream = store.OpenFile(file_name, FileMode.Open, FileAccess.Read))
                            {
                                using (MediaLibrary library = new MediaLibrary())
                                {
                                    library.SavePicture(file_name, stream);
                                }
                            }

                            store.DeleteFile(file_name);
                        }

                        this.editedImageChanged = false;

                        try
                        {
                            MessageBox.Show(AppResources.MessageBoxMessageImageSavedInfo, AppResources.MessageBoxHeaderInfo, MessageBoxButton.OK);
                        }
                        catch (Exception)
                        {
                            // Ignore
                        }
                    }
                    catch (Exception ex)
                    {
                        try
                        {
                            MessageBox.Show(AppResources.MessageBoxMessageImageSaveError + " " + ex.Message.ToString(), AppResources.MessageBoxHeaderError, MessageBoxButton.OK);
                        }
                        catch (Exception)
                        {
                            // Ignore
                        }
                    }
                }
            }
        }
Esempio n. 10
0
    protected override void Init()
    {
        base.Init();

        // Not interested in non singleton instance
        if (instance != this)
        {
            return;
        }

        // Create compoennts
#if USES_ADDRESS_BOOK
        if (addressBook == null)
        {
            addressBook = AddComponentBasedOnPlatformOnlyIfRequired <AddressBook>();
        }
#endif

#if USES_BILLING
        if (billing == null)
        {
            billing = AddComponentBasedOnPlatformOnlyIfRequired <Billing>();
        }
#endif

#if USES_CLOUD_SERVICES
        if (cloudServices == null)
        {
            cloudServices = AddComponentBasedOnPlatformOnlyIfRequired <CloudServices>();
        }
#endif

#if USES_GAME_SERVICES
        if (gameServices == null)
        {
            gameServices = AddComponentBasedOnPlatformOnlyIfRequired <GameServices>();
        }
#endif

#if USES_MEDIA_LIBRARY
        if (mediaLibrary == null)
        {
            mediaLibrary = AddComponentBasedOnPlatformOnlyIfRequired <MediaLibrary>();
        }
#endif

#if USES_NETWORK_CONNECTIVITY
        if (networkConnectivity == null)
        {
            networkConnectivity = AddComponentBasedOnPlatformOnlyIfRequired <NetworkConnectivity>();
        }
#endif

#if USES_NOTIFICATION_SERVICE
        if (notificationService == null)
        {
            notificationService = CachedGameObject.AddComponentIfNotFound <NotificationService>();
        }
#endif

#if USES_SHARING
        if (sharing == null)
        {
            sharing = AddComponentBasedOnPlatformOnlyIfRequired <Sharing>();
        }
#endif

#if USES_TWITTER
        if (twitter == null)
        {
            twitter = AddComponentBasedOnPlatformOnlyIfRequired <Twitter>();
        }
#endif

        if (userInterface == null)
        {
            userInterface = AddComponentBasedOnPlatformOnlyIfRequired <UI>();
        }

        if (utility == null)
        {
            utility = CachedGameObject.AddComponentIfNotFound <Utility>();
        }

#if USES_WEBVIEW
        if (webview == null)
        {
            webview = CachedGameObject.AddComponentIfNotFound <WebViewNative>();
        }
#endif

#if USES_SOOMLA_GROW
        if (soomlaGrowService == null)
        {
            soomlaGrowService = AddComponentBasedOnPlatformOnlyIfRequired <SoomlaGrowService>();
        }
#endif
    }
Esempio n. 11
0
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                var pass = (Pass)value;

                return(MediaLibrary.GetImage(_imageNames[pass]));
            }
 public void GetTracksAsync(MediaLibrary.Album album,
     Action<List<MediaLibrary.Track>, object, Exception> callback, object state)
 {
     lock (_syncLock)
     {
         Tuple<Action<List<MediaLibrary.Track>, object, Exception>, object> innerState =
             new Tuple<Action<List<MediaLibrary.Track>, object, Exception>, object>(callback, state);
         QueueRequest(new GetTracksDelegate(LibraryServiceClient.GetTracksAsync), new GetTracksRequest(album), innerState);
     }
 }
 public void PlayTrack(MediaLibrary.Track track,
     Action<MediaState, object, Exception> callback, object state)
 {
     lock (_syncLock)
     {
         Tuple<Action<MediaState, object, Exception>, object> innerState = new Tuple<Action<MediaState, object, Exception>, object>(callback, state);
         QueueRequest(new PlayTrackDelegate(PlaybackServiceClient.PlayTrackAsync), new PlayTrackRequest(track.ConvertToTrack()), innerState);
     }
 }
Esempio n. 14
0
        //
        // //
        //

        private Picture GetPictureObject(string path)
        {
            int length = 0;

            string [] aPath = PathParts(path, out length);

            if (length == 0)
            {
                return(null);
            }
            else
            {
                bool bPictures   = false;
                int  iLevelStart = 0;
                if (length > 0)
                {
                    if (aPath[0].ToLower().CompareTo("pictures") == 0)
                    {
                        bPictures   = true;
                        iLevelStart = 1;
                    }
                }
                if (length > 1)
                {
                    //Known Folder integration...
                    if (aPath[0].ToLower().CompareTo("media library") == 0)
                    {
                        if (aPath[1].ToLower().CompareTo("pictures") == 0)
                        {
                            bPictures   = true;
                            iLevelStart = 2;
                        }
                    }
                }

                if (bPictures)
                {
                    MediaLibrary MedLib = new MediaLibrary();
                    PictureAlbum pa     = MedLib.RootPictureAlbum;

                    bool bHit = false;
                    for (int iPos = iLevelStart; iPos < (length - 1); iPos++)
                    {
                        foreach (PictureAlbum paHit in pa.Albums)
                        {
                            if (paHit.Name.ToLower().CompareTo(aPath[iPos].ToLower()) == 0)
                            {
                                bHit = true;
                                pa   = paHit;
                                break;
                            }
                        }
                        if (!bHit)
                        {
                            return(null);                                //Album not found...
                        }
                    }

                    if (pa.Pictures.Count == 0)
                    {
                        return(null);                                             //No Pictures...
                    }
                    int    iPInd = -1;
                    string sFn   = aPath[length - 1];
                    int    iDot  = sFn.IndexOf(')');
                    if (iDot >= 0)
                    {
                        iPInd = Int32.Parse(sFn.Substring(0, iDot));
                        sFn   = sFn.Substring(iDot + 2);
                    }
                    sFn = sFn.ToLower();

                    if (iPInd >= 0 && iPInd < pa.Pictures.Count)
                    {
                        if (pa.Pictures[iPInd].Name.ToLower().CompareTo(sFn) == 0)
                        {
                            return(pa.Pictures[iPInd]);
                        }
                    }

                    foreach (Picture pHit in pa.Pictures)
                    {
                        if (pHit.Name.ToLower().CompareTo(sFn) == 0)
                        {
                            return(pHit);
                        }
                    }

                    return(null);
                }
                else
                {
                    return(null);
                }
            }

            //return null;
        }
Esempio n. 15
0
        private void SetAlbumArtAge(MediaLibrary.Album album)
        {
            lock (_syncLock)
            {
                bool isCurrentArtYoungest = false;
                if (_albumArtAge.ContainsKey(album.ID))
                {
                    isCurrentArtYoungest = (_albumArtAge[album.ID] == 0);
                    if (!isCurrentArtYoungest)
                    {
                        _albumArtAge[album.ID] = 0;
                    }
                }
                else
                {
                    _albumArtAge.Add(album.ID, 0);
                }

                List<string> keys = new List<string>();
                if (!isCurrentArtYoungest)
                {
                    foreach (string key in _albumArtAge.Keys)
                    {
                        keys.Add(key);

                    }

                    foreach (string key in keys)
                    {
                        if (string.Equals(key, album.ID))
                        {
                            _albumArtAge[key] = 0;
                        }
                        else
                        {
                            _albumArtAge[key]++;
                        }
                    }
                }
            }

            TrimExcessAlbumArt();
        }
Esempio n. 16
0
 private void FireAlbumArtDownloaded(MediaLibrary.Album album, BitmapImage albumArt)
 {
     if (_albumArtDownloaded != null)
     {
         _albumArtDownloaded(this, new EventArgs<MediaLibrary.Album, BitmapImage>(album, albumArt));
     }
 }
Esempio n. 17
0
        private void DownloadAlbumArt(MediaLibrary.Album album)
        {
            App.GetService<IRequestService>().GetAlbumArtByAlbumAsync(album,
                    (innerAlbum, imageData, state, error) =>
                    {
                        BitmapImage albumArt = null;
                        if (error == null && imageData != null && imageData.Length > 0)
                        {
                            albumArt = new BitmapImage();
                            if (imageData != null)
                            {
                                try
                                {
                                    using (MemoryStream artStream = new MemoryStream(imageData))
                                    {
                                        albumArt.SetSource(artStream);
                                    }
                                }
                                catch (Exception)
                                {
                                    albumArt = null;
                                }
                            }
                        }

                        lock (_syncLock)
                        {
                            if (_albumArtAge.ContainsKey(innerAlbum.ID))
                            {
                                if (_albumArtCache.ContainsKey(innerAlbum.ID))
                                {
                                    _albumArtCache[innerAlbum.ID] = albumArt;
                                }
                                else
                                {
                                    _albumArtCache.Add(innerAlbum.ID, albumArt);
                                }
                            }

                            FireAlbumArtDownloaded(innerAlbum, _albumArtCache[innerAlbum.ID]);
                        }

                        // Now, start the timer up again
                        StartTimer(0, 0);
                    }, null);
        }
Esempio n. 18
0
        public void GetAlbumArtAsync(MediaLibrary.Album album)
        {
            if (string.IsNullOrEmpty(album.ID))
            {
                return;
            }

            SetAlbumArtAge(album);

            if (_albumArtCache.ContainsKey(album.ID))
            {
                FireAlbumArtDownloaded(album, _albumArtCache[album.ID]);
            }
            else
            {
                lock (_requestLock)
                {
                    _queuedRequests.Add(album);
                    StartTimer(0, 300);
                }
            }
        }
Esempio n. 19
0
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            // Get a dictionary of query string keys and values.
            var queryStrings = NavigationContext.QueryString;

            // Ensure that there is at least one key in the query string, and check whether the "token" key is present.
            if (queryStrings.ContainsKey("token"))
            {
                _navigatedFrom = "Share";

                if (App.ViewModel.Attachments == null || (App.ViewModel.Attachments != null && App.ViewModel.Attachments.Count < 6))
                {
                    // Retrieve the photo from the media library using the token passed to the app.
                    var library          = new MediaLibrary();
                    var photoFromLibrary = library.GetPictureFromToken(queryStrings["token"]);

                    // Create a BitmapImage object and add set it as the image control source.
                    // To retrieve a full-resolution image, use the GetImage() method instead.
                    var fileName = Path.GetFileName(photoFromLibrary.Name);
                    fileName = new TimeSpan(DateTime.Now.Ticks - DateTime.MinValue.Ticks).TotalMilliseconds + fileName;

                    App.ViewModel.AddAttachment(photoFromLibrary.GetPreviewImage(), fileName,
                                                RayzItAttachment.ContentType.Image);
                }
                else
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show("Photo could not be attached. Limit exceeded.",
                                                                                    "Warning", MessageBoxButton.OK));
                }

                NavigationContext.QueryString.Clear();
            }

            if (queryStrings.ContainsKey("FileId"))
            {
                _navigatedFrom = "Share";

                if (App.ViewModel.Attachments == null || (App.ViewModel.Attachments != null && App.ViewModel.Attachments.Count < 6))
                {
                    // Retrieve the photo from the media library using the token passed to the app.
                    var library          = new MediaLibrary();
                    var photoFromLibrary = library.GetPictureFromToken(queryStrings["FileId"]);

                    // Create a BitmapImage object and add set it as the image control source.
                    // To retrieve a full-resolution image, use the GetImage() method instead.
                    var fileName = Path.GetFileName(photoFromLibrary.Name);
                    fileName = new TimeSpan(DateTime.Now.Ticks - DateTime.MinValue.Ticks).TotalMilliseconds + fileName;

                    App.ViewModel.AddAttachment(photoFromLibrary.GetPreviewImage(), fileName,
                                                RayzItAttachment.ContentType.Image);
                }
                else
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show("Photo could not be attached. Limit exceeded.",
                                                                                    "Warning", MessageBoxButton.OK));
                }

                NavigationContext.QueryString.Clear();
            }

            string msg;

            if (queryStrings.TryGetValue("NavigatedFrom", out msg))
            {
                _navigatedFrom = msg;
                NavigationContext.QueryString.Clear();
            }

            UpdateAttachmentsVisibility();
            UpdateApplicationBar();
            UpdateRayzHint();
            FocusTextBox();
        }
Esempio n. 20
0
        // Instance constructor
        public MusicPresenter()
        {
            // Make this class a singleton
            if (MusicPresenter.Current != null)
            {
                this.Composers = MusicPresenter.Current.Composers;
                return;
            }

            MediaLibrary mediaLib = new MediaLibrary();
            Dictionary <string, List <AlbumInfo> > albumsByComposer =
                new Dictionary <string, List <AlbumInfo> >();

            foreach (Album album in mediaLib.Albums)
            {
                int indexOfColon = album.Name.IndexOf(':');

                // Check for pathological cases
                if (indexOfColon != -1 &&
                    // Colon at beginning of album name
                    (indexOfColon == 0 ||
                     // Colon at end of album name
                     indexOfColon == album.Name.Length - 1 ||
                     // nothing before colon
                     album.Name.Substring(0, indexOfColon).Trim().Length == 0 ||
                     // nothing after colon
                     album.Name.Substring(indexOfColon + 1).Trim().Length == 0))
                {
                    indexOfColon = -1;
                }

                // Main logic for albums with composers
                if (indexOfColon != -1)
                {
                    string[] albumComposers  = album.Name.Substring(0, indexOfColon).Split(',');
                    string   shortAlbumName  = album.Name.Substring(indexOfColon + 1).Trim();
                    bool     atLeastOneEntry = false;

                    foreach (string composer in albumComposers)
                    {
                        string trimmedComposer = composer.Trim();

                        if (trimmedComposer.Length > 0)
                        {
                            atLeastOneEntry = true;

                            if (!albumsByComposer.ContainsKey(trimmedComposer))
                            {
                                albumsByComposer.Add(trimmedComposer, new List <AlbumInfo>());
                            }

                            albumsByComposer[trimmedComposer].Add(new AlbumInfo(shortAlbumName, album));
                        }
                    }

                    // Another pathological case: Just commas before colon
                    if (!atLeastOneEntry)
                    {
                        indexOfColon = -1;
                    }
                }

                // The "Other" category is for albums without composers
                if (indexOfColon == -1)
                {
                    if (!albumsByComposer.ContainsKey("Other"))
                    {
                        albumsByComposer.Add("Other", new List <AlbumInfo>());
                    }

                    albumsByComposer["Other"].Add(new AlbumInfo(album.Name, album));
                }
            }

            mediaLib.Dispose();

            // Transfer Dictionary keys to List for sorting
            List <string> composerList = new List <string>();

            foreach (string composer in albumsByComposer.Keys)
            {
                composerList.Add(composer);
            }

            (composerList as List <string>).Sort();

            // Construct Composers property
            Composers = new List <ComposerInfo>();

            foreach (string composer in composerList)
            {
                Composers.Add(new ComposerInfo(composer, albumsByComposer[composer]));
            }

            Current = this;
        }
Esempio n. 21
0
        private async Task <Photo> ProcessBitmap()
        {
            WriteableBitmap originalImage  = new WriteableBitmap(this.OriginalPhoto.PhotoImage);
            WriteableBitmap processedImage = new WriteableBitmap(originalImage.PixelWidth, originalImage.PixelHeight);
            MediaLibrary    library        = new MediaLibrary();

            int      horizontalResolution = this.HorizontalResolution;
            int      verticalResolution   = this.VerticalResolution;
            int      panelWidth           = (int)(processedImage.PixelWidth / horizontalResolution);
            int      panelHeight          = (int)(processedImage.PixelHeight / verticalResolution);
            DateTime startTime            = DateTime.Now;
            await Task.Run(() =>
            {
                double originalRatio = originalImage.PixelWidth / (double)originalImage.PixelHeight;
                for (int i = 0; i < verticalResolution; i++)
                {
                    for (int j = 0; j < horizontalResolution; j++)
                    {
                        int top            = panelHeight *i;
                        int left           = panelWidth *j;
                        Color averageColor = originalImage.GetAverageColor(top, left, panelHeight, panelWidth);

                        //// uses tinted original image
                        if (this.UseOriginalPhoto)
                        {
                            processedImage.Blit(new Rect(left, top, panelWidth, panelHeight), originalImage, new Rect(0, 0, originalImage.PixelWidth, originalImage.PixelHeight), averageColor, WriteableBitmapExtensions.BlendMode.None);
                        }
                        else
                        {
                            //// uses photo from library
                            //// cos sie jebie. zoptymalizowac to:
                            //// jak przechowywac dane w bazie? jak porownywac by bylo bardziej efektywnie (bez konwersji do koloru moze)
                            //// moze pozbyc sie klasy photo ? dorzucic tylko etension methods

                            try
                            {
                                var nearestColor = averageColor.FindNearestColorMatch(this.photoDictionary.Select(x => x.PhotoColor));
                                var photo        = library.Pictures.Single(x => x.Name == this.photoDictionary.First(y => y.PhotoColor == nearestColor.ToString()).PhotoName);
                                Action putImage  = delegate()
                                {
                                    BitmapImage sourceImage = new BitmapImage();
                                    sourceImage.SetSource(photo.GetImage());
                                    WriteableBitmap matchedPicture = new WriteableBitmap(sourceImage);
                                    //// zle skaluje powinno brac pod uwage orginalne i  przetworzone obrazy. kwadraty?
                                    double sourceRatio = matchedPicture.PixelWidth / (double)matchedPicture.PixelHeight;
                                    double selectedWidth;
                                    double selectedHeight;
                                    double selectedX = 0;
                                    double selectedY = 0;

                                    if (Math.Abs(originalRatio - sourceRatio) < 0.1)
                                    {
                                        selectedWidth  = matchedPicture.PixelWidth;
                                        selectedHeight = matchedPicture.PixelHeight;
                                    }
                                    else if (originalRatio > sourceRatio)
                                    {
                                        selectedWidth  = matchedPicture.PixelWidth;
                                        selectedHeight = Enumerable.Min(new[] { matchedPicture.PixelWidth *sourceRatio, matchedPicture.PixelHeight });
                                        selectedY      = (matchedPicture.PixelHeight - selectedHeight) / 2;
                                    }
                                    else
                                    {
                                        selectedWidth  = Enumerable.Min(new[] { matchedPicture.PixelHeight / sourceRatio, matchedPicture.PixelWidth });
                                        selectedHeight = matchedPicture.PixelHeight;
                                        selectedX      = (matchedPicture.PixelWidth - selectedWidth) / 2;
                                    }

                                    var sourceRect = new Rect(selectedX, selectedY, selectedWidth, selectedHeight);

                                    processedImage.Blit(new Rect(left, top, panelWidth, panelHeight), matchedPicture, sourceRect, WriteableBitmapExtensions.BlendMode.None);
                                };

                                Deployment.Current.Dispatcher.BeginInvoke(putImage);
                            }
                            catch (Exception ex)
                            {
                                GoogleAnalytics.EasyTracker.GetTracker().SendException(ex.Message, false);
                                MessageBox.Show(ex.Message);
                            }
                        }
                    }
                }
            });

            if (this.UseOriginalPhoto)
            {
                GoogleAnalytics.EasyTracker.GetTracker().SendEvent("Collage created", "Created from original.", "Processing time: " + DateTime.Now.Subtract(startTime).ToString(), 0);
            }
            else
            {
                GoogleAnalytics.EasyTracker.GetTracker().SendEvent("Collage created", "Created from library.", "Processing time: " + DateTime.Now.Subtract(startTime).ToString(), 0);
            }

            this.IsBusy = false;
            return(new Photo(processedImage));
        }
Esempio n. 22
0
 public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
 {
     return(MediaLibrary.GetImage(
                GetTemplateName((CardColor[])value) + ".png"));
 }
 public void GetAlbumsByArtistAsync(MediaLibrary.Artist artist, Action<List<MediaLibrary.Album>, object, Exception> callback, object state)
 {
     lock (_syncLock)
     {
         Tuple<Action<List<MediaLibrary.Album>, object, Exception>, object> innerState =
             new Tuple<Action<List<MediaLibrary.Album>, object, Exception>, object>(callback, state);
         QueueRequest(new GetAlbumsByArtistDelegate(LibraryServiceClient.GetAlbumsByArtistAsync), new GetAlbumsByArtistRequest(artist), innerState);
     }
 }
 private void LibraryServiceClient_PingCompleted(object sender, MediaLibrary.PingCompletedEventArgs e)
 {
     if (RequestCompleted(e.Error))
     {
         Tuple<Action<object, Exception>, object> innerState = (Tuple<Action<object, Exception>, object>)e.UserState;
         if (innerState.Item1 != null)
         {
             innerState.Item1.Invoke(innerState.Item2, e.Error);
         }
     }
 }
Esempio n. 25
0
        private PictureAlbum GetPictureAlbumObject(string path)
        {
            int length = 0;

            string [] aPath = PathParts(path, out length);

            if (length == 0)
            {
                return(null);
            }
            else
            {
                bool bPictures   = false;
                int  iLevelStart = 0;
                if (length > 0)
                {
                    if (aPath[0].ToLower().CompareTo("pictures") == 0)
                    {
                        bPictures   = true;
                        iLevelStart = 1;
                    }
                }
                if (length > 1)
                {
                    //Known Folder integration...
                    if (aPath[0].ToLower().CompareTo("media library") == 0)
                    {
                        if (aPath[1].ToLower().CompareTo("pictures") == 0)
                        {
                            bPictures   = true;
                            iLevelStart = 2;
                        }
                    }
                }

                if (bPictures)
                {
                    MediaLibrary MedLib = new MediaLibrary();
                    PictureAlbum pa     = MedLib.RootPictureAlbum;

                    bool bHit = false;
                    for (int iPos = iLevelStart; iPos < length; iPos++)
                    {
                        foreach (PictureAlbum paHit in pa.Albums)
                        {
                            if (paHit.Name.ToLower().CompareTo(aPath[iPos].ToLower()) == 0)
                            {
                                bHit = true;
                                pa   = paHit;
                                break;
                            }
                        }
                        if (!bHit)
                        {
                            return(null);                                //Album not found...
                        }
                    }

                    return(pa);
                }
                else
                {
                    return(null);
                }
            }

            //return null;
        }
Esempio n. 26
0
        //---------------------------------------------------------------------------------------------------------------------------------



        //Bilder in Listbox laden
        //---------------------------------------------------------------------------------------------------------
        void GetImages(string action)
        {
            //Listbox leeren
            datalist.Clear();

            //Wenn alle Bilder ausgewählt werden
            if (action == "allPictures")
            {
                imgPictures = "all";
                action      = "first";
            }

            //Wenn gespeicherte Bilder ausgewählt werden
            if (action == "savedPictures")
            {
                imgPictures = "saved";
                action      = "first";
            }

            //Bei allen Bildern
            if (imgPictures == "all")
            {
                //Bei allen Bildern
                MediaLibrary mediaLibrary = new MediaLibrary();
                var          pictures     = mediaLibrary.Pictures;

                //Beim ersten laden
                if (action == "first")
                {
                    //Variabeln erstellen
                    imgGes   = pictures.Count;
                    imgStart = 0;
                    if (imgGes >= (imgStart + 199))
                    {
                        imgEnd = imgStart + 199;
                    }
                    else
                    {
                        imgEnd = (pictures.Count - 1);
                    }
                    imgArea    = 1;
                    imgAreaGes = (imgGes / 200) + 1;
                }

                //Wenn nächste
                if (action == "next")
                {
                    //Prüfen ob möglich
                    if (imgArea < imgAreaGes)
                    {
                        imgArea++;
                        imgStart = imgStart + 200;
                        if (imgGes >= (imgStart + 199))
                        {
                            imgEnd = imgStart + 199;
                        }
                        else
                        {
                            imgEnd = (pictures.Count - 1);
                        }
                    }
                }

                //Wenn vorherige
                if (action == "previous")
                {
                    //Prüfen ob möglich
                    if (imgArea > 1)
                    {
                        imgArea--;
                        imgStart = imgStart - 200;
                        if (imgGes >= (imgStart + 199))
                        {
                            imgEnd = imgStart + 199;
                        }
                        else
                        {
                            imgEnd = (pictures.Count - 1);
                        }
                    }
                }

                //Bilder auslesen und in ListBox schreiben
                for (int i = imgStart; i <= imgEnd; i++)
                {
                    try
                    {
                        BitmapImage image = new BitmapImage();
                        image.SetSource(pictures[i].GetThumbnail());
                        datalist.Add(new ClassMediaImage((i), image));
                    }
                    catch
                    {
                    }
                }
            }

            //Bei gespeicherten Bildern
            else
            {
                //Bei saved Pictures
                MediaLibrary mediaLibrary = new MediaLibrary();
                var          pictures     = mediaLibrary.SavedPictures;

                //Beim ersten laden
                if (action == "first")
                {
                    //Variabeln erstellen
                    imgGes   = pictures.Count;
                    imgStart = 0;
                    if (imgGes >= (imgStart + 199))
                    {
                        imgEnd = imgStart + 199;
                    }
                    else
                    {
                        imgEnd = (pictures.Count - 1);
                    }
                    imgArea    = 1;
                    imgAreaGes = (imgGes / 200) + 1;
                }

                //Wenn nächste
                if (action == "next")
                {
                    //Prüfen ob möglich
                    if (imgArea < imgAreaGes)
                    {
                        imgArea++;
                        imgStart = imgStart + 200;
                        if (imgGes >= (imgStart + 199))
                        {
                            imgEnd = imgStart + 199;
                        }
                        else
                        {
                            imgEnd = (pictures.Count - 1);
                        }
                    }
                }

                //Wenn vorherige
                if (action == "previous")
                {
                    //Prüfen ob möglich
                    if (imgArea > 1)
                    {
                        imgArea--;
                        imgStart = imgStart - 200;
                        if (imgGes >= (imgStart + 199))
                        {
                            imgEnd = imgStart + 199;
                        }
                        else
                        {
                            imgEnd = (pictures.Count - 1);
                        }
                    }
                }

                //Bilder auslesen und in ListBox schreiben
                for (int i = imgStart; i <= imgEnd; i++)
                {
                    try
                    {
                        BitmapImage image = new BitmapImage();
                        image.SetSource(pictures[i].GetThumbnail());
                        datalist.Add(new ClassMediaImage((i), image));
                    }
                    catch
                    {
                    }
                }
            }

            //Daten in Listbox schreiben
            LBImages.ItemsSource = datalist;

            //AppBar erstellen
            CreateAppBar();
        }
Esempio n. 27
0
 private void Initialize()
 {
     ThreadPool.QueueUserWorkItem((WaitCallback)(o =>
     {
         try
         {
             Stopwatch stopwatch = Stopwatch.StartNew();
             List <AlbumHeader> albumHeaders = new List <AlbumHeader>();
             using (MediaLibrary mediaLibrary = new MediaLibrary())
             {
                 using (PictureAlbum rootPictureAlbum = mediaLibrary.RootPictureAlbum)
                 {
                     PictureAlbumCollection pictureAlbumCollection = rootPictureAlbum != null ? rootPictureAlbum.Albums : (PictureAlbumCollection)null;
                     if (pictureAlbumCollection != null)
                     {
                         if (pictureAlbumCollection.Count > 0)
                         {
                             using (IEnumerator <PictureAlbum> enumerator = pictureAlbumCollection.GetEnumerator())
                             {
                                 while (((IEnumerator)enumerator).MoveNext())
                                 {
                                     PictureAlbum current = enumerator.Current;
                                     if (current != null)
                                     {
                                         PictureCollection pictures = current.Pictures;
                                         if (pictures != null)
                                         {
                                             string str = current.Name ?? "";
                                             AlbumHeader albumHeader1 = new AlbumHeader();
                                             albumHeader1.AlbumId = str;
                                             albumHeader1.AlbumName = str;
                                             int count = pictures.Count;
                                             albumHeader1.PhotosCount = count;
                                             AlbumHeader albumHeader2 = albumHeader1;
                                             string albumName = albumHeader2.AlbumName;
                                             if (!(albumName == "Camera Roll"))
                                             {
                                                 if (!(albumName == "Saved Pictures"))
                                                 {
                                                     if (!(albumName == "Sample Pictures"))
                                                     {
                                                         if (albumName == "Screenshots")
                                                         {
                                                             albumHeader2.AlbumName = CommonResources.AlbumScreenshots;
                                                             albumHeader2.OrderNo = 3;
                                                         }
                                                         else
                                                         {
                                                             albumHeader2.OrderNo = int.MaxValue;
                                                         }
                                                     }
                                                     else
                                                     {
                                                         albumHeader2.AlbumName = CommonResources.AlbumSamplePictures;
                                                         albumHeader2.OrderNo = 2;
                                                     }
                                                 }
                                                 else
                                                 {
                                                     albumHeader2.AlbumName = CommonResources.AlbumSavedPictures;
                                                     albumHeader2.OrderNo = 1;
                                                 }
                                             }
                                             else
                                             {
                                                 albumHeader2.AlbumName = CommonResources.AlbumCameraRoll;
                                                 albumHeader2.OrderNo = 0;
                                             }
                                             Picture picture = ((IEnumerable <Picture>)pictures).FirstOrDefault <Picture>();
                                             if (picture != null)
                                             {
                                                 try
                                                 {
                                                     albumHeader2.ImageStream = picture.GetThumbnail();
                                                 }
                                                 catch
                                                 {
                                                 }
                                                 try
                                                 {
                                                     picture.Dispose();
                                                 }
                                                 catch
                                                 {
                                                 }
                                             }
                                             albumHeaders.Add(albumHeader2);
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
             stopwatch.Stop();
             Execute.ExecuteOnUIThread((Action)(() =>
             {
                 this._albums.Clear();
                 foreach (IEnumerable <AlbumHeader> source in albumHeaders.OrderBy <AlbumHeader, int>((Func <AlbumHeader, int>)(ah => ah.OrderNo)).Partition <AlbumHeader>(2))
                 {
                     List <AlbumHeader> list = source.ToList <AlbumHeader>();
                     AlbumHeaderTwoInARow albumHeaderTwoInArow = new AlbumHeaderTwoInARow()
                     {
                         AlbumHeader1 = list[0]
                     };
                     if (list.Count > 1)
                     {
                         albumHeaderTwoInArow.AlbumHeader2 = list[1];
                     }
                     this._albums.Add(albumHeaderTwoInArow);
                 }
                 this._isLoaded = true;
                 this.NotifyPropertyChanged <string>((Expression <Func <string> >)(() => this.FooterText));
                 this.NotifyPropertyChanged <Visibility>((Expression <Func <Visibility> >)(() => this.FooterTextVisibility));
             }));
         }
         catch (Exception ex)
         {
             Logger.Instance.ErrorAndSaveToIso("Failed to read gallery albums", ex);
         }
     }));
 }
Esempio n. 28
0
        //Aktion ausführen
        void LoadImageToPanel()
        {
            //Verschiebung zurücksetzen
            transform.TranslateX = 0;
            transform.TranslateY = 0;

            //Bei allen Bildern
            if (imgPictures == "all")
            {
                //Bei allen Bildern
                MediaLibrary mediaLibrary = new MediaLibrary();
                var          pictures     = mediaLibrary.Pictures;

                //Bilder auslesen und in Cut Panel schreiben
                try
                {
                    //Bild in Temp Bitmap laden
                    tempBitmap.SetSource(pictures[ImagesToAdd[ImageNow]].GetImage());

                    //Bild Maße neu berechnen
                    if (tempBitmap.PixelWidth < tempBitmap.PixelHeight)
                    {
                        nWidth = imgSize;
                        int perc = 100 * 100000 / tempBitmap.PixelWidth * imgSize / 100000;
                        nHeight = tempBitmap.PixelHeight * 100000 / 100 * perc / 100000;
                    }
                    else if (tempBitmap.PixelWidth > tempBitmap.PixelHeight)
                    {
                        nHeight = imgSize;
                        int perc = 100 * 100000 / tempBitmap.PixelHeight * imgSize / 100000;
                        nWidth = tempBitmap.PixelWidth * 100000 / 100 * perc / 100000;
                    }
                    else
                    {
                        nWidth  = imgSize;
                        nHeight = imgSize;
                    }

                    //Bild Maße neu erstellen
                    tempBitmap = tempBitmap.Resize(nWidth, nHeight, WriteableBitmapExtensions.Interpolation.Bilinear);

                    //Bild in Cut Bild ausgeben
                    CutImage.Height = nHeight;
                    CutImage.Width  = nWidth;
                    CutImage.Source = tempBitmap;
                }
                catch
                {
                }
            }

            //Bei gespeicherten Bildern
            else
            {
                //Bei saved Pictures
                MediaLibrary mediaLibrary = new MediaLibrary();
                var          pictures     = mediaLibrary.SavedPictures;

                //Bilder auslesen und in Cut Panel schreiben
                try
                {
                    //Bild in Temp Bitmap laden
                    tempBitmap.SetSource(pictures[ImagesToAdd[ImageNow]].GetImage());

                    //Bild Maße neu berechnen
                    if (tempBitmap.PixelWidth < tempBitmap.PixelHeight)
                    {
                        nWidth = imgSize;
                        int perc = 100 * 100000 / tempBitmap.PixelWidth * imgSize / 100000;
                        nHeight = tempBitmap.PixelHeight * 100000 / 100 * perc / 100000;
                    }
                    else if (tempBitmap.PixelWidth > tempBitmap.PixelHeight)
                    {
                        nHeight = imgSize;
                        int perc = 100 * 100000 / tempBitmap.PixelHeight * imgSize / 100000;
                        nWidth = tempBitmap.PixelWidth * 100000 / 100 * perc / 100000;
                    }
                    else
                    {
                        nWidth  = imgSize;
                        nHeight = imgSize;
                    }

                    //Bild Maße neu erstellen
                    tempBitmap = tempBitmap.Resize(nWidth, nHeight, WriteableBitmapExtensions.Interpolation.Bilinear);

                    //Bild in Cut Bild ausgeben
                    CutImage.Height = nHeight;
                    CutImage.Width  = nWidth;
                    CutImage.Source = tempBitmap;
                }
                catch
                {
                }
            }
        }
Esempio n. 29
0
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                var cardName = (string)value;

                return(MediaLibrary.GetCardImage(GetCardImageName(cardName)));
            }
Esempio n. 30
0
        //---------------------------------------------------------------------------------------------------------



        //Button Automatisch schneiden
        //---------------------------------------------------------------------------------------------------------
        private void BtnAutoCut(object sender, EventArgs e)
        {
            //Schleife erstellen um Bilder automatisch zu schneiden
            for (int i = ImageNow; i < ImagesToAdd_c; i++)
            {
                //Bei allen Bildern
                if (imgPictures == "all")
                {
                    //Bei allen Bildern
                    MediaLibrary mediaLibrary = new MediaLibrary();
                    var          pictures     = mediaLibrary.Pictures;

                    //Bilder auslesen und in Cut Panel schreiben
                    try
                    {
                        //Bild in Temp Bitmap laden
                        tempBitmap.SetSource(pictures[ImagesToAdd[ImageNow]].GetImage());

                        //Bild Maße neu berechnen
                        if (tempBitmap.PixelWidth < tempBitmap.PixelHeight)
                        {
                            //Neue Größer errechnen
                            nWidth = imgSize;
                            int perc = 100 * 100000 / tempBitmap.PixelWidth * imgSize / 100000;
                            nHeight = tempBitmap.PixelHeight * 100000 / 100 * perc / 100000;
                            //Bild Maße neu erstellen
                            tempBitmap = tempBitmap.Resize(nWidth, nHeight, WriteableBitmapExtensions.Interpolation.Bilinear);
                            //Bild schneiden
                            tempBitmap = tempBitmap.Crop(0, ((nHeight - imgSize) / 2), imgSize, imgSize);
                        }
                        else if (tempBitmap.PixelWidth > tempBitmap.PixelHeight)
                        {
                            //Neue Größer errechnen
                            nHeight = imgSize;
                            int perc = 100 * 100000 / tempBitmap.PixelHeight * imgSize / 100000;
                            nWidth = tempBitmap.PixelWidth * 100000 / 100 * perc / 100000;
                            //Bild Maße neu erstellen
                            tempBitmap = tempBitmap.Resize(nWidth, nHeight, WriteableBitmapExtensions.Interpolation.Bilinear);
                            //Bild schneiden
                            tempBitmap = tempBitmap.Crop(((nWidth - imgSize) / 2), 0, imgSize, imgSize);
                        }
                        else
                        {
                            //Neue Größer errechnen
                            nWidth  = imgSize;
                            nHeight = imgSize;
                            //Bild Maße neu erstellen
                            tempBitmap = tempBitmap.Resize(nWidth, nHeight, WriteableBitmapExtensions.Interpolation.Bilinear);
                        }

                        //Image Count erhöhen
                        ImageCount++;
                        string ImageName = Convert.ToString(ImageCount);
                        while (ImageName.Length < 8)
                        {
                            ImageName = "0" + ImageName;
                        }
                        //Image Count speichern
                        IsolatedStorageFile file       = IsolatedStorageFile.GetUserStoreForApplication();
                        FileStream          filestream = file.CreateFile("Settings/ImageCount.txt");
                        StreamWriter        sw         = new StreamWriter(filestream);
                        sw.WriteLine(Convert.ToString(ImageCount));
                        sw.Flush();
                        filestream.Close();

                        //Datei in Isolated Storage schreiben
                        var userStoreForApplication   = IsolatedStorageFile.GetUserStoreForApplication();
                        var isolatedStorageFileStream = userStoreForApplication.CreateFile("/Folders/" + Folder + "/" + ImageName + ".jpg");
                        int ImgHeight = tempBitmap.PixelHeight;
                        int ImgWidth  = tempBitmap.PixelWidth;
                        tempBitmap.SaveJpeg(isolatedStorageFileStream, tempBitmap.PixelWidth, tempBitmap.PixelHeight, 0, 80);
                        isolatedStorageFileStream.Close();

                        //Thumbnail erstellen
                        int percent;
                        int newWidth;
                        int newHeight;
                        //Wenn breiter als hoch
                        if (tempBitmap.PixelWidth > tempBitmap.PixelHeight)
                        {
                            percent   = 100 * 1000 / tempBitmap.PixelWidth * 150 / 1000;
                            newHeight = tempBitmap.PixelHeight * 1000 / 100 * percent / 1000;
                            newWidth  = 150;
                        }
                        //Wenn höher als breit
                        else
                        {
                            percent   = 100 * 1000 / tempBitmap.PixelHeight * 150 / 1000;
                            newWidth  = tempBitmap.PixelWidth * 1000 / 100 * percent / 1000;
                            newHeight = 150;
                        }
                        //Bild verkleinern
                        tempBitmap = tempBitmap.Resize(newWidth, newHeight, WriteableBitmapExtensions.Interpolation.Bilinear);

                        //Thumbnail speichern
                        isolatedStorageFileStream = userStoreForApplication.CreateFile("/Thumbs/" + Folder + "/" + ImageName + ".jpg");
                        tempBitmap.SaveJpeg(isolatedStorageFileStream, tempBitmap.PixelWidth, tempBitmap.PixelHeight, 0, 80);
                        isolatedStorageFileStream.Close();

                        //ImagesAll bearbeiten
                        ImagesAll += ImageName + ".jpg/";
                        //Images.dat speichern
                        filestream = file.CreateFile("/Thumbs/" + Folder + ".dat");
                        sw         = new StreamWriter(filestream);
                        sw.WriteLine(ImagesAll);
                        sw.Flush();
                        filestream.Close();

                        //ImgNow erhöhen
                        ImageNow++;
                    }
                    catch
                    {
                    }
                }

                //Bei gespeicherten Bildern
                else
                {
                    //Bei saved Pictures
                    MediaLibrary mediaLibrary = new MediaLibrary();
                    var          pictures     = mediaLibrary.SavedPictures;

                    //Bilder auslesen und in Cut Panel schreiben
                    try
                    {
                        //Bild in Temp Bitmap laden
                        tempBitmap.SetSource(pictures[ImagesToAdd[ImageNow]].GetImage());

                        //Bild Maße neu berechnen
                        if (tempBitmap.PixelWidth < tempBitmap.PixelHeight)
                        {
                            //Neue Größer errechnen
                            nWidth = imgSize;
                            int perc = 100 * 100000 / tempBitmap.PixelWidth * imgSize / 100000;
                            nHeight = tempBitmap.PixelHeight * 100000 / 100 * perc / 100000;
                            //Bild Maße neu erstellen
                            tempBitmap = tempBitmap.Resize(nWidth, nHeight, WriteableBitmapExtensions.Interpolation.Bilinear);
                            //Bild schneiden
                            tempBitmap = tempBitmap.Crop(0, ((nHeight - imgSize) / 2), imgSize, imgSize);
                        }
                        else if (tempBitmap.PixelWidth > tempBitmap.PixelHeight)
                        {
                            //Neue Größer errechnen
                            nHeight = imgSize;
                            int perc = 100 * 100000 / tempBitmap.PixelHeight * imgSize / 100000;
                            nWidth = tempBitmap.PixelWidth * 100000 / 100 * perc / 100000;
                            //Bild Maße neu erstellen
                            tempBitmap = tempBitmap.Resize(nWidth, nHeight, WriteableBitmapExtensions.Interpolation.Bilinear);
                            //Bild schneiden
                            tempBitmap = tempBitmap.Crop(((nWidth - imgSize) / 2), 0, imgSize, imgSize);
                        }
                        else
                        {
                            //Neue Größer errechnen
                            nWidth  = imgSize;
                            nHeight = imgSize;
                            //Bild Maße neu erstellen
                            tempBitmap = tempBitmap.Resize(nWidth, nHeight, WriteableBitmapExtensions.Interpolation.Bilinear);
                        }

                        //Image Count erhöhen
                        ImageCount++;
                        string ImageName = Convert.ToString(ImageCount);
                        while (ImageName.Length < 8)
                        {
                            ImageName = "0" + ImageName;
                        }
                        //Image Count speichern
                        IsolatedStorageFile file       = IsolatedStorageFile.GetUserStoreForApplication();
                        FileStream          filestream = file.CreateFile("Settings/ImageCount.txt");
                        StreamWriter        sw         = new StreamWriter(filestream);
                        sw.WriteLine(Convert.ToString(ImageCount));
                        sw.Flush();
                        filestream.Close();

                        //Datei in Isolated Storage schreiben
                        var userStoreForApplication   = IsolatedStorageFile.GetUserStoreForApplication();
                        var isolatedStorageFileStream = userStoreForApplication.CreateFile("/Folders/" + Folder + "/" + ImageName + ".jpg");
                        int ImgHeight = tempBitmap.PixelHeight;
                        int ImgWidth  = tempBitmap.PixelWidth;
                        tempBitmap.SaveJpeg(isolatedStorageFileStream, tempBitmap.PixelWidth, tempBitmap.PixelHeight, 0, 80);
                        isolatedStorageFileStream.Close();

                        //Thumbnail erstellen
                        int percent;
                        int newWidth;
                        int newHeight;
                        //Wenn breiter als hoch
                        if (tempBitmap.PixelWidth > tempBitmap.PixelHeight)
                        {
                            percent   = 100 * 1000 / tempBitmap.PixelWidth * 150 / 1000;
                            newHeight = tempBitmap.PixelHeight * 1000 / 100 * percent / 1000;
                            newWidth  = 150;
                        }
                        //Wenn höher als breit
                        else
                        {
                            percent   = 100 * 1000 / tempBitmap.PixelHeight * 150 / 1000;
                            newWidth  = tempBitmap.PixelWidth * 1000 / 100 * percent / 1000;
                            newHeight = 150;
                        }
                        //Bild verkleinern
                        tempBitmap = tempBitmap.Resize(newWidth, newHeight, WriteableBitmapExtensions.Interpolation.Bilinear);

                        //Thumbnail speichern
                        isolatedStorageFileStream = userStoreForApplication.CreateFile("/Thumbs/" + Folder + "/" + ImageName + ".jpg");
                        tempBitmap.SaveJpeg(isolatedStorageFileStream, tempBitmap.PixelWidth, tempBitmap.PixelHeight, 0, 80);
                        isolatedStorageFileStream.Close();

                        //ImagesAll bearbeiten
                        ImagesAll += ImageName + ".jpg/";
                        //Images.dat speichern
                        filestream = file.CreateFile("/Thumbs/" + Folder + ".dat");
                        sw         = new StreamWriter(filestream);
                        sw.WriteLine(ImagesAll);
                        sw.Flush();
                        filestream.Close();

                        //ImgNow erhöhen
                        ImageNow++;
                    }
                    catch
                    {
                    }
                }
            }

            //Cut zurücksetzen
            CutRoot.Margin     = new Thickness(-600, 0, 0, 0);
            CutRoot.Visibility = System.Windows.Visibility.Collapsed;
            //AppBar zurückstellen
            CreateAppBar();
            //MenuOpene zurücksetzen
            MenuOpen = false;
        }
Esempio n. 31
0
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                var id = (int)value;

                return(MediaLibrary.GetAvatar(id));
            }
Esempio n. 32
0
        //[Fact]

        public DraftFacts()
        {
            MediaLibrary.LoadSets();
        }
Esempio n. 33
0
 public AlbumViewModel(MediaLibrary.Album album)
 {
     Album = album;
 }
Esempio n. 34
0
        /// <summary>
        /// Loads local audio information and creates a model for local artists to be shown in Favourites view.
        /// </summary>
        public void LoadData()
        {
            mediaLib = new MediaLibrary();
            int totalTrackCount  = 0;
            int totalArtistCount = 0;

            foreach (Artist a in mediaLib.Artists)
            {
                if (a.Songs.Count <= 0)
                {
                    continue;                     // Skip artists without tracks
                }
                string artist     = a.Name;
                int    trackCount = a.Songs.Count;
                int    playCount  = 0;

                // Check the play count of artist's tracks
                foreach (Song s in a.Songs)
                {
                    playCount += s.PlayCount;
                }

                // Insert artist before less played artists..
                bool artistAdded = false;
                for (int i = 1; i < LocalAudio.Count; i++) // Index 0 reserved for title item
                {
                    if (Convert.ToInt16(LocalAudio[i].PlayCount) < playCount)
                    {
                        this.LocalAudio.Insert(i, new ArtistModel()
                        {
                            Name            = artist,
                            LocalTrackCount = Convert.ToString(trackCount),
                            PlayCount       = Convert.ToString(playCount)
                        });
                        artistAdded = true;
                        break;
                    }
                }

                // ...Or add artist to the end of the list if it's least played
                if (artistAdded == false)
                {
                    this.LocalAudio.Add(new ArtistModel()
                    {
                        Name            = artist,
                        LocalTrackCount = Convert.ToString(trackCount),
                        PlayCount       = Convert.ToString(playCount)
                    });
                }

                totalTrackCount += trackCount;
                totalArtistCount++;
            }

            // Continue with only the top 20 favourite artists
            int removeIndex = App.ViewModel.LocalAudio.Count - 1;

            while (removeIndex > 20)
            {
                App.ViewModel.LocalAudio.RemoveAt(removeIndex);
                removeIndex--;
            }

            // Divide local artists into two "size categories"
            foreach (ArtistModel m in App.ViewModel.LocalAudio)
            {
                if (m.Name.Contains("TitlePlaceholder"))
                {
                    continue;
                }
                if (Convert.ToInt16(m.LocalTrackCount) > (totalTrackCount / totalArtistCount))
                {
                    //m.ItemHeight = "146";
                    //m.ItemWidth = "146";
                    m.ItemHeight = "205";
                    m.ItemWidth  = "205";
                }
                else
                {
                    m.ItemHeight = "102";
                    m.ItemWidth  = "205";
                }
            }

            if (LocalAudio.Count <= 1) // There's always the favourites title
            {
                NoFavouritesVisibility = Visibility.Visible;
            }
            else
            {
                NoFavouritesVisibility = Visibility.Collapsed;
            }

            this.IsDataLoaded = true;
        }
Esempio n. 35
0
        public async Task GetSequences()
        {
            try
            {
                var list = new List <Sequence>();
                if (App.SaveToCameraRollEnabled)
                {
                    using (MediaLibrary library = new MediaLibrary())
                    {
                        foreach (PictureAlbum album in library.RootPictureAlbum.Albums)
                        {
                            if (album.Name == "Camera Roll")
                            {
                                var images = from r in album.Pictures where r.Name.StartsWith("mapi_thumb_") select r;
                                foreach (var item in images)
                                {
                                    string      sequenceId = "noseq";
                                    BitmapImage bi         = new BitmapImage();
                                    using (var stream = item.GetImage())
                                    {
                                        bi.SetSource(stream);
                                    }

                                    var split = item.Name.Split(new char[] { '#' }, StringSplitOptions.None);
                                    if (split.Length == 2)
                                    {
                                        sequenceId = split[1];
                                    }
                                    if (list.Count == 0)
                                    {
                                        list.Add(new Sequence()
                                        {
                                            CanDeleteVisibility = App.SaveToCameraRollEnabled ? Visibility.Collapsed : Visibility.Visible,
                                            SequenceId          = sequenceId,
                                            ThumbBitmapImage    = bi,
                                            TimeStamp           = item.Date,
                                            Count = 1
                                        });
                                    }
                                    else
                                    {
                                        var seq = list.Find(r => r.SequenceId == sequenceId);
                                        if (seq != null)
                                        {
                                            seq.Count++;
                                        }
                                        else
                                        {
                                            list.Add(new Sequence()
                                            {
                                                CanDeleteVisibility = App.SaveToCameraRollEnabled ? Visibility.Collapsed : Visibility.Visible,
                                                SequenceId          = sequenceId,
                                                ThumbBitmapImage    = bi,
                                                TimeStamp           = item.Date,
                                                Count = 1
                                            });
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (!storage.DirectoryExists("shared\\transfers"))
                        {
                            m_photos = new ObservableCollection <Photo>();
                        }

                        var folder = await ApplicationData.Current.LocalFolder.GetFolderAsync("shared\\transfers");

                        var images = await folder.GetFilesAsync();

                        var imagesNoThumb = from r in images where !r.Name.StartsWith("thumb_") select r;
                        foreach (var item in imagesNoThumb)
                        {
                            string sequenceId = "noseq";
                            var    split      = item.Name.Split(new char[] { '#' }, StringSplitOptions.None);
                            if (split.Length == 2)
                            {
                                sequenceId = split[1];
                            }

                            var thumbFile = await folder.GetFileAsync("thumb_" + item.Name);

                            if (list.Count == 0)
                            {
                                list.Add(new Sequence()
                                {
                                    SequenceId       = sequenceId,
                                    ThumbFile        = thumbFile,
                                    ThumbBitmapImage = new BitmapImage(new Uri(thumbFile.Path))
                                    {
                                        CreateOptions = BitmapCreateOptions.IgnoreImageCache
                                    },
                                    TimeStamp = item.DateCreated.DateTime,
                                    Count     = 1
                                });
                            }
                            else
                            {
                                var seq = list.Find(r => r.SequenceId == sequenceId);
                                if (seq != null)
                                {
                                    seq.Count++;
                                }
                                else
                                {
                                    list.Add(new Sequence()
                                    {
                                        SequenceId       = sequenceId,
                                        ThumbFile        = thumbFile,
                                        ThumbBitmapImage = new BitmapImage(new Uri(thumbFile.Path))
                                        {
                                            CreateOptions = BitmapCreateOptions.IgnoreImageCache
                                        },
                                        TimeStamp = item.DateCreated.DateTime,
                                        Count     = 1
                                    });
                                }
                            }
                        }
                    }
                }

                Sequences = new ObservableCollection <Sequence>(list);
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR: " + ex.Message);
                m_photos = null;
            }
        }
Esempio n. 36
0
        /// <summary>
        /// Upload files to MEGA Cloud Service
        /// </summary>
        public static async void Upload()
        {
            SdkService.MegaSdk.retryPendingConnections();

            // Get the date of the last uploaded file
            // Needed so that we do not upload the same file twice
            var lastUploadDate = SettingsService.LoadSettingFromFile <DateTime>("LastUploadDate");

            // Open the phone's Media Library
            MediaLibrary mediaLibrary;

            try { mediaLibrary = new MediaLibrary(); }
            catch (Exception e)
            {
                // Error opening the Media Library
                LogService.Log(MLogLevel.LOG_LEVEL_ERROR, "Error opening the Media Library", e);
                scheduledAgent.NotifyComplete();
                return;
            }

            using (mediaLibrary)
            {
                List <Picture> pictures;

                var selectDate = lastUploadDate;
                // Find all pictures taken after the last upload date
                try { pictures = mediaLibrary.Pictures.Where(p => p.Date > selectDate).OrderBy(p => p.Date).ToList(); }
                catch (Exception e)
                {
                    // Error getting the pictures taken after the last upload date
                    LogService.Log(MLogLevel.LOG_LEVEL_ERROR, "Error getting pictures from the media library", e);
                    scheduledAgent.NotifyComplete();
                    return;
                }

                if (!pictures.Any())
                {
                    // No pictures is not an error. Maybe all pictures have already been uploaded
                    // Just finish the task for this run
                    LogService.Log(MLogLevel.LOG_LEVEL_INFO, "No new items to upload");
                    scheduledAgent.NotifyComplete();
                    return;
                }

                var cameraUploadNode = await scheduledAgent.GetCameraUploadsNode();

                if (cameraUploadNode == null)
                {
                    // No camera upload node found or created
                    // Just finish this run and try again next time
                    LogService.Log(MLogLevel.LOG_LEVEL_ERROR, "No camera uploads folder");
                    scheduledAgent.NotifyComplete();
                    return;
                }

                // Loop all available pictures for upload action
                foreach (var picture in pictures)
                {
                    try
                    {
                        // Retreive the picture bytes as stream
                        using (var imageStream = picture.GetImage())
                        {
                            // Make sure the stream pointer is at the start of the stream
                            imageStream.Position = 0;

                            // Calculate time for fingerprint check
                            DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
                            TimeSpan diff   = picture.Date.ToUniversalTime() - origin;
                            ulong    mtime  = (ulong)Math.Floor(diff.TotalSeconds);

                            // Get the unique fingerprint of the file
                            string fingerprint = SdkService.MegaSdk.getFileFingerprint(new MegaInputStream(imageStream), mtime);

                            // Check if the fingerprint is already in the subfolders of the Camera Uploads
                            var mNode = SdkService.MegaSdk.getNodeByFingerprint(fingerprint, cameraUploadNode);

                            // If node already exists then save the node date and proceed with the next node
                            if (mNode != null)
                            {
                                SettingsService.SaveSettingToFile <DateTime>("LastUploadDate", picture.Date);
                                continue; // skip to next picture
                            }

                            // Create a temporary local path to save the picture for upload
                            string newFilePath = Path.Combine(scheduledAgent.GetTemporaryUploadFolder(), picture.Name);

                            // Reset back to start
                            // Because fingerprint action has moved the position
                            imageStream.Position = 0;

                            // Copy file to local storage to be able to upload
                            using (var fs = new FileStream(newFilePath, FileMode.Create))
                            {
                                await imageStream.CopyToAsync(fs);

                                await fs.FlushAsync();

                                fs.Close();
                            }

                            // Init the upload
                            SdkService.MegaSdk.startUploadWithMtimeTempSource(newFilePath, cameraUploadNode, mtime, true);
                            break;
                        }
                    }
                    catch (OutOfMemoryException e)
                    {
                        // Something went wrong (could be memory limit)
                        // Just finish this run and try again next time
                        LogService.Log(MLogLevel.LOG_LEVEL_ERROR, "Error during the item upload", e);
                        scheduledAgent.NotifyComplete();
                    }
                    catch (Exception e)
                    {
                        // Send log, process the error and try again
                        LogService.Log(MLogLevel.LOG_LEVEL_ERROR, "Error during the item upload", e);
                        ErrorProcessingService.ProcessFileError(picture.Name, picture.Date);
                        Upload();
                        return;
                    }
                }
            }
        }
Esempio n. 37
0
        private void saveImage_Click(object sender, EventArgs e)
        {
            if (!NetWorkAvailable())
            {
                MessageBox.Show("Sorry, There is some problem with internet connectivity");
                return;
            }

            if (!string.IsNullOrEmpty(_imagePath))
            {
                string imagePath = _imagePath;
                if (imagePath.ToLower().Contains("cdn.mobstac.com"))
                {
                    imagePath = imagePath.Replace(".jpg&w=400", ".jpg");
                }
                string fileName  = Path.GetFileName(imagePath);
                var    webClient = new WebClient();
                webClient.OpenReadCompleted += (object websender, OpenReadCompletedEventArgs ex) =>
                {
                    try
                    {
                        if (ex.Cancelled == true)
                        {
                            MessageBox.Show("Some problem in downloaing the image");
                            return;
                        }

                        if (ex.Error != null)
                        {
                            MessageBox.Show(string.Format("Some problem in downloaing the image: {0}", ex.Error.ToString()));
                            return;
                        }
                        else
                        {
                            var streamResourceInfo      = new StreamResourceInfo(ex.Result, null);
                            var userStoreForApplication = IsolatedStorageFile.GetUserStoreForApplication();
                            if (userStoreForApplication.FileExists(fileName))
                            {
                                userStoreForApplication.DeleteFile(fileName);
                            }

                            var isolatedStorageFileStream = userStoreForApplication.CreateFile(fileName);

                            var bitmapImage = new BitmapImage {
                                CreateOptions = BitmapCreateOptions.None
                            };
                            bitmapImage.SetSource(streamResourceInfo.Stream);

                            var writeableBitmap = new WriteableBitmap(bitmapImage);
                            writeableBitmap.SaveJpeg(isolatedStorageFileStream, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight, 0, 85);

                            isolatedStorageFileStream.Close();
                            isolatedStorageFileStream = userStoreForApplication.OpenFile(fileName, FileMode.Open, FileAccess.Read);

                            // Save the image to the camera roll or saved pictures album.
                            var mediaLibrary = new MediaLibrary();
                            // Save the image to the saved pictures album.
                            Picture picture = mediaLibrary.SavePicture(fileName, isolatedStorageFileStream);
                            if (picture.Name.Contains(fileName))
                            {
                                DispatcherHelper.UIDispatcher.BeginInvoke(() =>
                                {
                                    MessageBox.Show(string.Format("successfully saved the image in picture hub"));
                                });
                            }
                            else
                            {
                                DispatcherHelper.UIDispatcher.BeginInvoke(() =>
                                {
                                    MessageBox.Show(string.Format("Sorry, Failed to save the image"));
                                });
                            }
                            isolatedStorageFileStream.Close();
                        }
                    }
                    catch (Exception)
                    {
                        DispatcherHelper.UIDispatcher.BeginInvoke(() =>
                        {
                            MessageBox.Show(string.Format("Sorry, Failed to save the image"));
                        });
                    }
                };

                webClient.OpenReadAsync(new Uri(imagePath, UriKind.RelativeOrAbsolute));
            }
            else
            {
                MessageBox.Show("Sorry, failed to save the image");
            }
        }
Esempio n. 38
0
        private async void SendMediaExecute()
        {
            if (MediaLibrary.SelectedCount > 0)
            {
                if (ApplicationSettings.Current.IsSendGrouped && MediaLibrary.SelectedCount > 1)
                {
                    var items = MediaLibrary.Where(x => x.IsSelected).ToList();
                    var group = new List <StorageMedia>(Math.Min(items.Count, 10));

                    foreach (var item in items)
                    {
                        group.Add(item);

                        if (group.Count == 10)
                        {
                            await SendGroupedAsync(group);

                            group = new List <StorageMedia>(Math.Min(items.Count, 10));
                        }
                    }

                    if (group.Count > 0)
                    {
                        await SendGroupedAsync(group);
                    }
                }
                else
                {
                    foreach (var storage in MediaLibrary.Where(x => x.IsSelected))
                    {
                        if (storage is StoragePhoto photo)
                        {
                            var storageFile = await photo.GetFileAsync();
                            await SendPhotoAsync(storageFile, storage.Caption, storage.IsForceFile, storage.Ttl);
                        }
                        else if (storage is StorageVideo video)
                        {
                            await SendVideoAsync(storage.File, storage.Caption, video.IsMuted, storage.IsForceFile, storage.Ttl, await video.GetEncodingAsync(), video.GetTransform());
                        }
                    }
                }

                return;
            }

            var picker = new FileOpenPicker();

            picker.ViewMode = PickerViewMode.Thumbnail;
            picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            picker.FileTypeFilter.AddRange(Constants.MediaTypes);

            var files = await picker.PickMultipleFilesAsync();

            if (files != null && files.Count > 0)
            {
                var storages = new ObservableCollection <StorageMedia>();

                foreach (var file in files)
                {
                    var storage = await StorageMedia.CreateAsync(file, true);

                    if (storage != null)
                    {
                        storages.Add(storage);
                    }
                }

                SendMediaExecute(storages, storages[0]);
            }
        }
Esempio n. 39
0
        /// <summary>
        /// Handles result of capture to save image information
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e">stores information about current captured image</param>
        private void cameraTask_Completed(object sender, PhotoResult e)
        {
            if (e.Error != null)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR));
                return;
            }

            switch (e.TaskResult)
            {
            case TaskResult.OK:
                try
                {
                    string fileName = System.IO.Path.GetFileName(e.OriginalFileName);

                    // Save image in media library
                    MediaLibrary library = new MediaLibrary();
                    Picture      image   = library.SavePicture(fileName, e.ChosenPhoto);

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

                    // Save image in isolated storage

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

                    byte[] imageBytes = new byte[rotImageStream.Length];
                    rotImageStream.Read(imageBytes, 0, imageBytes.Length);
                    rotImageStream.Dispose();
                    string pathLocalStorage = this.SaveImageToLocalStorage(fileName, isoFolder, imageBytes);
                    imageBytes = null;
                    // Get image data
                    MediaFile data = new MediaFile(pathLocalStorage, image);

                    this.files.Add(data);

                    if (files.Count < this.captureImageOptions.Limit)
                    {
                        cameraTask.Show();
                    }
                    else
                    {
                        DispatchCommandResult(new PluginResult(PluginResult.Status.OK, files));
                        files.Clear();
                    }
                }
                catch (Exception)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Error capturing image."));
                }
                break;

            case TaskResult.Cancel:
                if (files.Count > 0)
                {
                    // User canceled operation, but some images were made
                    DispatchCommandResult(new PluginResult(PluginResult.Status.OK, files));
                    files.Clear();
                }
                else
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Canceled."));
                }
                break;

            default:
                if (files.Count > 0)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.OK, files));
                    files.Clear();
                }
                else
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Did not complete!"));
                }
                break;
            }
        }
        public Task <int> GetAvailableImagesFromRepositoryAsync()
        {
            var m = new MediaLibrary();

            return(Task.FromResult(m.Pictures.Count));
        }
Esempio n. 41
0
 public void setSongs(MediaLibrary library)
 {
     songs = library.Songs;
 }
        public Task <int> GetImageCountAsync()
        {
            var m = new MediaLibrary();

            return(Task.FromResult(m.Pictures.Count));
        }
Esempio n. 43
0
        /// <summary>
        /// Handles result of capture to save image information
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e">stores information about current captured image</param>
        private void cameraTask_Completed(object sender, PhotoResult e)
        {
            if (e.Error != null)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR));
                return;
            }

            switch (e.TaskResult)
            {
            case TaskResult.OK:
                try
                {
                    string fileName = System.IO.Path.GetFileName(e.OriginalFileName);

                    // Save image in media library
                    MediaLibrary library = new MediaLibrary();
                    Picture      image   = library.SavePicture(fileName, e.ChosenPhoto);

                    // Save image in isolated storage

                    // we should return stream position back after saving stream to media library
                    e.ChosenPhoto.Seek(0, SeekOrigin.Begin);
                    byte[] imageBytes = new byte[e.ChosenPhoto.Length];
                    e.ChosenPhoto.Read(imageBytes, 0, imageBytes.Length);
                    string pathLocalStorage = this.SaveImageToLocalStorage(fileName, isoFolder, imageBytes);

                    // Get image data
                    MediaFile data = new MediaFile(pathLocalStorage, image);

                    this.files.Add(data);

                    if (files.Count < this.captureImageOptions.Limit)
                    {
                        cameraTask.Show();
                    }
                    else
                    {
                        DispatchCommandResult(new PluginResult(PluginResult.Status.OK, files, "navigator.device.capture._castMediaFile"));
                        files.Clear();
                    }
                }
                catch (Exception ex)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Error capturing image."));
                }
                break;

            case TaskResult.Cancel:
                if (files.Count > 0)
                {
                    // User canceled operation, but some images were made
                    DispatchCommandResult(new PluginResult(PluginResult.Status.OK, files, "navigator.device.capture._castMediaFile"));
                    files.Clear();
                }
                else
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Canceled."));
                }
                break;

            default:
                if (files.Count > 0)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.OK, files, "navigator.device.capture._castMediaFile"));
                    files.Clear();
                }
                else
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Did not complete!"));
                }
                break;
            }
        }
Esempio n. 44
0
        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;
            }
        }
Esempio n. 45
0
        public override string [] GetFolderNames(string path, string wildcard, bool bIncludeHidden, bool bStartWithInfChr)
        {
            int length = 0;

            string [] aPath = PathParts(path, out length);

            if (length == 0 && (wildcard.Length == 0 || wildcard == "*.*"))
            {
                if (bStartWithInfChr)
                {
                    return new String [] { "nPictures" }
                }
                ;                                                           //Normal...
                else
                {
                    return new String [] { "Pictures" }
                };
            }
            else if (length == 1 && aPath[0].ToLower().CompareTo("media library") == 0 && (wildcard.Length == 0 || wildcard == "*.*"))
            {
                //Known Folder integration...
                if (bStartWithInfChr)
                {
                    return new String [] { "nPictures" }
                }
                ;                                                           //Normal...
                else
                {
                    return new String [] { "Pictures" }
                };
            }
            else
            {
                bool bPictures   = false;
                int  iLevelStart = 0;
                if (length > 0)
                {
                    if (aPath[0].ToLower().CompareTo("pictures") == 0)
                    {
                        bPictures   = true;
                        iLevelStart = 1;
                    }
                }
                if (length > 1)
                {
                    //Known Folder integration...
                    if (aPath[0].ToLower().CompareTo("media library") == 0)
                    {
                        if (aPath[1].ToLower().CompareTo("pictures") == 0)
                        {
                            bPictures   = true;
                            iLevelStart = 2;
                        }
                    }
                }

                if (bPictures)
                {
                    MediaLibrary MedLib = new MediaLibrary();

                    PictureAlbum pa = MedLib.RootPictureAlbum;

                    bool bHit = false;
                    for (int iPos = iLevelStart; iPos < length; iPos++)
                    {
                        foreach (PictureAlbum paHit in pa.Albums)
                        {
                            if (paHit.Name.ToLower().CompareTo(aPath[iPos].ToLower()) == 0)
                            {
                                bHit = true;
                                pa   = paHit;
                                break;
                            }
                        }
                        if (!bHit)
                        {
                            return new String [] {}
                        }
                        ;                                                            //Album not found...
                    }

                    if (pa.Albums.Count == 0)
                    {
                        return new String [] {}
                    }
                    ;                                                                       //No Sub Album...

                    RscWildCard wc = new RscWildCard(wildcard);

                    string [] astr = new String[pa.Albums.Count];

                    int iLenSave = astr.Length;
                    int i        = 0;
                    foreach (PictureAlbum paHit in pa.Albums)
                    {
                        if (wc.Wanted(paHit.Name))
                        {
                            if (bStartWithInfChr)
                            {
                                astr[i] = "n";                                   //Normal...
                            }
                            else
                            {
                                astr[i] = "";
                            }
                            astr[i] += paHit.Name;

                            i++;
                        }
                    }

                    if (i == 0)
                    {
                        return new String [] {}
                    }
                    ;                                                         //All filtered out...
                    if (i == iLenSave)
                    {
                        return(astr);                                    //All wanted...
                    }
                    //Not so nice... :(
                    string [] astr2 = new String[i];
                    for (int j = 0; j < i; j++)
                    {
                        astr2[j] = astr[j];
                    }

                    return(astr2);
                }
                else
                {
                    return(new String [] {});
                }
            }

            //return new String [] {};
        }
Esempio n. 46
0
 public AlbumClickedArgs(MediaLibrary.Album album)
 {
     Album = album;
 }