/// <summary> /// Asynchronously returns a list of all pictures in the specified album /// </summary> /// <param name="albumName">The name of the album</param> /// <param name="path">The path of the album</param> /// <returns>A list of all pictures in the specified album</returns> /// <remarks>The path parameter is not actually used in this Windows Phone implementation /// since the MediaLibrary API does not support picture or album retrieval with a path. Instead, we must walk /// the library looking for the album with the given albumName and then grab all the pictures in that album.</remarks> public Task<List<PictureViewModel>> GetPicturesAsync(string albumName, string path) { return Task.Run(delegate { List<PictureViewModel> result = new List<PictureViewModel>(); MediaLibrary mediaLib = new MediaLibrary(); // Find the album foreach (var album in mediaLib.RootPictureAlbum.Albums) { // Because the photo library API on Windows Phone doesn't expose the concept of "path", // we iterate and find the album based on the name. if (album.Name == albumName) { foreach (var pic in album.Pictures) { PictureViewModel pvm = new PictureViewModel(App.PictureService, albumName, pic.Name,String.Format("{0}|{1}",albumName, pic.Name),pic.Width, pic.Height); result.Add(pvm); } Debug.WriteLine("{0} pictures in {1}", result.Count(), albumName); break; } } return result; }); }
public static String TakeInIsolatedSotrage(UIElement elt, String name) { string imageFolder = "Shared/ShellContent/"; using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) { if (!myIsolatedStorage.DirectoryExists(imageFolder)) { myIsolatedStorage.CreateDirectory(imageFolder); } if (myIsolatedStorage.FileExists(name)) { myIsolatedStorage.DeleteFile(name); } string filePath = System.IO.Path.Combine(imageFolder, name); IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(filePath); var bmp = new WriteableBitmap(elt, null); var width = (int)bmp.PixelWidth; var height = (int)bmp.PixelHeight; using (var ms = new MemoryStream(width * height * 4)) { bmp.SaveJpeg(ms, width, height, 0, 100); ms.Seek(0, SeekOrigin.Begin); var lib = new MediaLibrary(); Extensions.SaveJpeg(bmp, fileStream, width, height, 0, 80); } fileStream.Close(); Debugger.Log(0, "", "isostore:/" + filePath); return "isostore:/"+filePath; } }
protected override async void OnNavigatedTo(NavigationEventArgs e) { // Get a dictionary of query string keys and values. IDictionary<string, string> queryStrings = this.NavigationContext.QueryString; // Check whether the app has been started by the photo edit picker of the Windows Phone System // More information about the photo edit picker here: http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202966(v=vs.105).aspx if (queryStrings.ContainsKey("FileId") && imageAlreadyLoaded == false) { imageAlreadyLoaded = true; // Retrieve the photo from the media library using the FileID passed to the app. MediaLibrary library = new MediaLibrary(); Picture photoFromLibrary = library.GetPictureFromToken(queryStrings["FileId"]); // Create a BitmapImage object and add set it as the PreviewImage BitmapImage bitmapFromPhoto = new BitmapImage(); bitmapFromPhoto.SetSource(photoFromLibrary.GetPreviewImage()); SetPreviewImage(bitmapFromPhoto); } // Every time we navigate to the MainPage we check if a filter has been selected on the FilterView page // If so, we apply this filter to the PreviewImage if (FilterSelectorView.SelectedFilter != null) { await ApplyFilter(FilterSelectorView.SelectedFilter, PreviewPicture); } }
private void OnPhotoChooserTaskCompleted(object sender, PhotoResult e) { var stream = e.ChosenPhoto; if (stream == null) { // If connected to Zune and debugging (WP7), the PhotoChooserTask won't open so we just pick the first image available. #if DEBUG var mediaLibrary = new MediaLibrary(); if (mediaLibrary.SavedPictures.Count > 0) { var firstPicture = mediaLibrary.SavedPictures[0]; stream = firstPicture.GetImage(); } #else return; #endif } var bitmapImage = new BitmapImage(); bitmapImage.SetSource(stream); //TODO: close stream? _writableBitmap = new WriteableBitmap(bitmapImage); pixelatedImage.Source = _writableBitmap; _originalPixels = new int[_writableBitmap.Pixels.Length]; _writableBitmap.Pixels.CopyTo(_originalPixels, 0); PixelateWriteableBitmap(); }
private void PopulateImageGrid() { MediaLibrary mediaLibrary = new MediaLibrary(); var pictures = mediaLibrary.Pictures; for (int i = 0; i < pictures.Count; i += Utilities.ImagesPerRow) { RowDefinition rd = new RowDefinition(); rd.Height = new GridLength(Utilities.GridRowHeight); grid1.RowDefinitions.Add(rd); int maxPhotosToProcess = (i + Utilities.ImagesPerRow < pictures.Count ? i + Utilities.ImagesPerRow : pictures.Count); int rowNumber = i / Utilities.ImagesPerRow; for (int j = i; j < maxPhotosToProcess; j++) { BitmapImage image = new BitmapImage(); image.SetSource(pictures[j].GetImage()); Image img = new Image(); img.Height = Utilities.ImageHeight; img.Stretch = Stretch.Fill; img.Width = Utilities.ImageWidth; img.HorizontalAlignment = HorizontalAlignment.Center; img.VerticalAlignment = VerticalAlignment.Center; img.Source = image; img.SetValue(Grid.RowProperty, rowNumber); img.SetValue(Grid.ColumnProperty, j - i); img.Tap += Image_Tap; grid1.Children.Add(img); } } }
protected override void OnNavigatedTo(NavigationEventArgs e) { imageDetails.Text = ""; IDictionary<string, string> queryStrings = NavigationContext.QueryString; string token = null; string source = null; if (queryStrings.ContainsKey("token")) { token = queryStrings["token"]; source = "Photos_Extra_Viewer"; } else if (queryStrings.ContainsKey("FileId")) { token = queryStrings["FileId"]; source = "Photos_Extra_Share"; } if (!string.IsNullOrEmpty(token)) { MediaLibrary mediaLib = new MediaLibrary(); Picture picture = mediaLib.GetPictureFromToken(token); currentImage = ImageUtil.GetBitmap(picture.GetImage()); photoContainer.Fill = new ImageBrush { ImageSource = currentImage }; imageDetails.Text = string.Format("Image from {0}.\nPicture name:\n{1}\nMedia library token:\n{2}", source, picture.Name, token); } imageDetails.Text += "\nUri: " + e.Uri.ToString(); }
/// <summary> /// Sets the background music to the sound with the given name. /// </summary> /// <param name="name">The name of the music to play.</param> public static void PlayMusic(string name) { currentSong = null; try { currentSong = content.Load<Song>(name); } catch (Exception e) { #if ZUNE //on the Zune we can go through the MediaLibrary to attempt //to find a matching song name. this functionality doesn't //exist on Windows or Xbox 360 at this time MediaLibrary ml = new MediaLibrary(); foreach (Song song in ml.Songs) if (song.Name == name) currentSong = song; #endif //if we didn't find the song, rethrow the exception if (currentSong == null) throw e; } MediaPlayer.Play(currentSong); }
/// <summary> /// Asynchronously returns a list of all albums in the picture library /// </summary> /// <returns>A list of all albums in the picture library</returns> public Task<List<PixPresenterPortableLib.AlbumViewModel>> GetAlbumsAsync() { return Task.Run(delegate { List<AlbumViewModel> result = new List<AlbumViewModel>(); MediaLibrary mediaLib = new MediaLibrary(); foreach (var album in mediaLib.RootPictureAlbum.Albums) { byte[] thumb = null; // Exclude empty picture albums if (album.Pictures.Count > 0) { Stream stream = album.Pictures[0].GetThumbnail(); using (BinaryReader br = new BinaryReader(stream)) { thumb = br.ReadBytes((int)stream.Length); } AlbumViewModel avm = new AlbumViewModel(App.AlbumService, album.Name, album.Name, thumb); avm.Name = album.Name; result.Add(avm); } } return result; }); }
/// <summary> /// Clicking on the save button saves the photo in DataContext.ImageStream to media library /// camera roll. Once image has been saved, the application will navigate back to the main page. /// </summary> private void saveButton_Click(object sender, EventArgs e) { try { // Reposition ImageStream to beginning, because it has been read already in the OnNavigatedTo method. _dataContext.ImageStream.Position = 0; MediaLibrary library = new MediaLibrary(); library.SavePictureToCameraRoll("CameraExplorer_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".jpg", _dataContext.ImageStream); // There should be no temporary file left behind using (var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) { var files = isolatedStorage.GetFileNames("CameraExplorer_*.jpg"); foreach (string file in files) { isolatedStorage.DeleteFile(file); //System.Diagnostics.Debug.WriteLine("Temp file deleted: " + file); } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Saving picture to camera roll failed: " + ex.HResult.ToString("x8") + " - " + ex.Message); } NavigationService.GoBack(); }
private void btnSalvar_Click(object sender, RoutedEventArgs e) { try { string _tmpImage = "tmpImage"; string _msgMensagem = "Imagem grava com sucesso!"; var store = IsolatedStorageFile.GetUserStoreForApplication(); if (store.FileExists(_tmpImage)) store.DeleteFile(_tmpImage); IsolatedStorageFileStream _stream = store.CreateFile(_tmpImage); WriteableBitmap _writeImage = new WriteableBitmap(_imagetmp); Extensions.SaveJpeg(_writeImage, _stream, _writeImage.PixelWidth, _writeImage.PixelHeight, 0, 100); _stream.Close(); _stream = store.OpenFile(_tmpImage, System.IO.FileMode.Open, System.IO.FileAccess.Read); MediaLibrary _mlibrary = new MediaLibrary(); _mlibrary.SavePicture(_stream.Name, _stream); _stream.Close(); btnSalvar.IsEnabled = false; lblStatus.Text = _msgMensagem; } catch (Exception error) { lblStatus.Text = error.Message; } }
public void saveImageDataToLibrary(string jsonArgs) { try { var options = JsonHelper.Deserialize<string[]>(jsonArgs); string imageData = options[0]; byte[] imageBytes = Convert.FromBase64String(imageData); using (var imageStream = new MemoryStream(imageBytes)) { imageStream.Seek(0, SeekOrigin.Begin); string fileName = String.Format("c2i_{0:yyyyMMdd_HHmmss}", DateTime.Now); var library = new MediaLibrary(); var picture = library.SavePicture(fileName, imageStream); if (picture.Name.Contains(fileName)) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, "Image saved: " + picture.Name)); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Failed to save image: " + picture.Name)); } } } catch (Exception ex) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ex.Message)); } }
public void TestAddingListOfSongs() { EZPlaylist playlist = new EZPlaylist("My Awesome Playlist"); MediaLibrary lib = new MediaLibrary(); if (lib.Songs.Count > 1) { List<SongInfo> list = new List<SongInfo>(); Song song = lib.Songs[0]; SongInfo si1 = new SongInfo(song.Artist.Name, song.Album.Name, song.Name, song.Duration, song.TrackNumber); list.Add(si1); song = lib.Songs[1]; SongInfo si2 = new SongInfo(song.Artist.Name, song.Album.Name, song.Name, song.Duration, song.TrackNumber); list.Add(si2); playlist.AddList(list.AsReadOnly()); Assert.IsTrue(playlist.Count == 2); Assert.IsTrue(playlist.Songs.Contains(si1)); Assert.IsTrue(playlist.Songs.Contains(si2)); } else { Assert.Fail("Can't test adding a song because there are no songs to add or there is only one song."); } }
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e) { MediaLibrary ml = new MediaLibrary(); List<Song> songlist = ml.Songs.ToList(); albums = new List<AlbumModel>(); String artist_name = null; if (NavigationContext.QueryString.TryGetValue("Artist", out artist_name)) { ArtistTextBlock.Text = artist_name; foreach(Artist a in ml.Artists) { if(a.Name == artist_name) { foreach (Album item in a.Albums) { albums.Add(new AlbumModel(item.Name, item.GetThumbnail())); } break; } } AlbumSelector.ItemsSource = albums; } }
// Constructor public MainPage() { InitializeComponent(); ml = new MediaLibrary(); gm = new List<GalleryModel>(); }
public static Boolean capture(int quality) { try { PhoneApplicationFrame frame = (PhoneApplicationFrame)Application.Current.RootVisual; WriteableBitmap bitmap = new WriteableBitmap((int)frame.ActualWidth, (int)frame.ActualHeight); bitmap.Render(frame, null); bitmap.Invalidate(); string fileName = DateTime.Now.ToString("'Capture'yyyyMMddHHmmssfff'.jpg'"); IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication(); if (storage.FileExists(fileName)) return false; IsolatedStorageFileStream stream = storage.CreateFile(fileName); bitmap.SaveJpeg(stream, bitmap.PixelWidth, bitmap.PixelHeight, 0, quality); stream.Close(); stream = storage.OpenFile(fileName, FileMode.Open, FileAccess.Read); MediaLibrary mediaLibrary = new MediaLibrary(); Picture picture = mediaLibrary.SavePicture(fileName, stream); stream.Close(); storage.DeleteFile(fileName); } catch (Exception e) { MessageBox.Show(e.Message); return false; } return true; }
public static string MatchLocalPathWithLibraryPath(string localPath) { var localFilename = FilenameFromPath(localPath); using (var library = new MediaLibrary()) { using (var pictures = library.Pictures) { for (int i = 0; i < pictures.Count; i++) { using (var picture = pictures[i]) { var libraryPath = picture.GetPath(); var libraryFilename = FilenameFromPath(libraryPath); if (localFilename == libraryFilename) { return libraryPath; } } } } } return null; }
// Sample code for building a localized ApplicationBar //private void BuildLocalizedApplicationBar() //{ // // Set the page's ApplicationBar to a new instance of ApplicationBar. // ApplicationBar = new ApplicationBar(); // // Create a new button and set the text value to the localized string from AppResources. // ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative)); // appBarButton.Text = AppResources.AppBarButtonText; // ApplicationBar.Buttons.Add(appBarButton); // // Create a new menu item with the localized string from AppResources. // ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText); // ApplicationBar.MenuItems.Add(appBarMenuItem); //} protected override void OnNavigatedTo(NavigationEventArgs e) { if (State.ContainsKey("customCamera")) { State.Remove("customCamera"); InitializeCamera(); } IDictionary<string, string> queryStrings = NavigationContext.QueryString; string action = null; if (queryStrings.ContainsKey("Action")) action = queryStrings["Action"]; string token = null; if (queryStrings.ContainsKey("FileId")) token = queryStrings["FileId"]; if (!string.IsNullOrEmpty(token)) { MediaLibrary mediaLib = new MediaLibrary(); Picture picture = mediaLib.GetPictureFromToken(token); currentImage = PictureDecoder.DecodeJpeg(picture.GetImage()); photoContainer.Fill = new ImageBrush { ImageSource = currentImage }; imageDetails.Text = string.Format("Image from {0} action.\nPicture name:\n{1}\nMedia library token:\n{2}", action, picture.GetPath(), token); } }
private void Button_Click(object sender, RoutedEventArgs e) { var api = ((App)App.Current).Api; api.CatalogUpdateCompleted += new EventHandler<EchoNestApiEventArgs>(api_CatalogUpdateCompleted); var songsActions = new List<CatalogAction<BMSong>>(); using (var mediaLib = new MediaLibrary()) { foreach (var song in mediaLib.Songs) { var catalogAction = new CatalogAction<BMSong>(); catalogAction.Action = CatalogAction<BMSong>.ActionType.update; catalogAction.Item = new BMSong { ItemId = Guid.NewGuid().ToString("D"), ArtistName = song.Artist.Name, SongName = song.Name, }; songsActions.Add(catalogAction); } } var catalog = new Catalog(); catalog.Id = catalogId.Text; catalog.SongActions = songsActions; api.CatalogUpdateAsync(catalog, null, null); }
protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); MediaLibrary library = new MediaLibrary(); if (NavigationContext.QueryString.ContainsKey(playSongKey)) { // Start über Hub-Verlauf // playingSong direkt übernehmen und starten string songName = NavigationContext.QueryString[playSongKey]; playingSong = library.Songs.FirstOrDefault(s => s.Name == songName); isFromHubHistory = true; } else if (MediaPlayer.State == MediaState.Playing) { // Aktuellen Song übernehmen playingSong = MediaPlayer.Queue.ActiveSong; } else { // Zufälligen Song auswählen Random r = new Random(); int songsCount = library.Songs.Count; if (songsCount > 0) { playingSong = library.Songs[r.Next(songsCount)]; } else { SongName.Text = "Keine Songs gefunden"; Play.IsEnabled = false; } } }
// Constructor public MainPage() { InitializeComponent(); library = new MediaLibrary(); photoChooser = new PhotoChooserTask(); photoChooser.Completed += photoChooser_Completed; }
/// <summary> /// Constructor for the Application object. /// </summary> public App() { BugSenseHandler.Instance.Init(this, "fbf56725"); // WTF Marketplace... WHY DO YOU NEED THIS OR YOU DONT DETECT MEDIALIB?! var library = new MediaLibrary(); // Global handler for uncaught exceptions. BugSenseHandler.Instance.UnhandledException += Application_UnhandledException; // Standard Silverlight initialization InitializeComponent(); // Phone-specific initialization InitializePhoneApplication(); // Show graphics profiling information while debugging. if (System.Diagnostics.Debugger.IsAttached) { // Display the current frame rate counters. //Application.Current.Host.Settings.EnableFrameRateCounter = true; // Show the areas of the app that are being redrawn in each frame. //Application.Current.Host.Settings.EnableRedrawRegions = true; // Enable non-production analysis visualization mode, // which shows areas of a page that are handed off to GPU with a colored overlay. //Application.Current.Host.Settings.EnableCacheVisualization = true; // Disable the application idle detection by setting the UserIdleDetectionMode property of the // application's PhoneApplicationService object to Disabled. // Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run // and consume battery power when the user is not using the phone. PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled; } }
void WebClientOpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { const string tempJpeg = "TempJPEG"; var streamResourceInfo = new StreamResourceInfo(e.Result, null); var userStoreForApplication = IsolatedStorageFile.GetUserStoreForApplication(); if (userStoreForApplication.FileExists(tempJpeg)) { userStoreForApplication.DeleteFile(tempJpeg); } var isolatedStorageFileStream = userStoreForApplication.CreateFile(tempJpeg); 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(tempJpeg, 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. mediaLibrary.SavePicture(string.Format("SavedPicture{0}.jpg", DateTime.Now), isolatedStorageFileStream); isolatedStorageFileStream.Close(); }
public BetterMediaPlayer(List<Song> songs) { this.songs = songs; currentSongIndex = 0; activeSong = songs.ElementAtOrDefault<Song>(currentSongIndex); using (MediaLibrary library = new MediaLibrary()) { collectionSongs = library.Songs.ToList(); } MediaPlayer.ActiveSongChanged += (s, e) => { if (MediaPlayer.Queue.ActiveSong == nextSong) { MoveNext(); } else if (MediaPlayer.Queue.ActiveSong == prevSong) { MovePrev(); } }; MediaPlayer.MediaStateChanged += (s, e) => { if (MediaPlayer.State == MediaState.Stopped) { MoveNext(); } if (MediaPlayer.State == MediaState.Playing) { timer.Change(0, 500); } else { timer.Change(Timeout.Infinite, Timeout.Infinite); } RaisePropertyChanged(StatePropertyName); }; timer = new Timer( x => RaisePropertyChanged(PlayPositionPropertyName), null, Timeout.Infinite, Timeout.Infinite); // Needed, otherwise our counting logic is completely thrown off // because the order is not maintained between the collection passed // to MediaPlayer.Play and MediaPlayer.Queue MediaPlayer.IsShuffled = false; // TODO Ask the user to take over the music // TODO Figure out how to clear existing playlist MediaPlayer.Stop(); // TODO Stop music when they quit the app }
public MainViewModel() { _library = new MediaLibrary(); this.Songs = new ObservableCollection<SongInfo>(); this.Albums = new ObservableCollection<AlbumInfo>(); this.Artists = new ObservableCollection<ArtistInfo>(); this.Playlists = new ObservableCollection<EZPlaylist>(); this.SongPlayingVM = new SongPlayingViewModel(new SongInfo()); }
public static void SaveToPhotoLibrary(this Texture2D texture, string filename) { MemoryStream memoryStream = new MemoryStream(); texture.SaveAsJpeg(memoryStream, texture.Width, texture.Height); memoryStream.Position = 0; MediaLibrary mediaLibrary = new MediaLibrary(); mediaLibrary.SavePicture(filename, memoryStream); memoryStream.Close(); }
public static SongCollection GetSongs() { using (SongHelper.library = new MediaLibrary()) { SongHelper.songs = library.Songs; SongHelper.playlists = library.Playlists; return songs; } }
public camera() { InitializeComponent(); mediaLib = new MediaLibrary(); myCam = new PhotoCamera(CameraType.Primary); myCam.CaptureCompleted += new EventHandler<CameraOperationCompletedEventArgs>(captureCompleted); myCam.CaptureImageAvailable += new EventHandler<ContentReadyEventArgs>(captureImageAvailable); viewfinderBrush.SetSource(myCam); }
private void PreparePopups() { if (theHelpPopup == null) { theHelpPopup = new Popup(); theHelpPopup.Child = new HelpPopup(); theHelpPopup.VerticalOffset = 200; theHelpPopup.HorizontalOffset = 0; theHelpPopup.Closed += (sender1, e1) => { this.ApplicationBar.IsVisible = true; }; } if (theSavePopup == null) { theSavePopup = new Popup(); theSavePopup.Child = new HelpSavePopup(); theSavePopup.VerticalOffset = 70; theSavePopup.HorizontalOffset = 0; theSavePopup.Closed += (sender1, e1) => { try { if (!backButtonPressedFlag) { var bitmap = new System.Windows.Media.Imaging.WriteableBitmap(this.LayoutRoot, null); using (var stream = new System.IO.MemoryStream()) { System.Windows.Media.Imaging.Extensions.SaveJpeg(bitmap, stream, bitmap.PixelWidth, bitmap.PixelHeight, 0, 100); stream.Position = 0; var mediaLib = new Microsoft.Xna.Framework.Media.MediaLibrary(); var datetime = System.DateTime.Now; var filename = System.String.Format("LockScreen-{0}-{1}-{2}-{3}-{4}", datetime.Year % 100, datetime.Month, datetime.Day, datetime.Hour, datetime.Minute); mediaLib.SavePicture(filename, stream); var toast = new ToastPrompt { Title = "Saved", Message = @"Your wallpaper is in ""Saved Pictures""" }; toast.Show(); } } backButtonPressedFlag = false; } finally { UpdateMockup(false); } }; } }
public void LoadData() { var m = new MediaLibrary(); foreach (var p in m.Playlists) { this.Playlists.Add(new PlaylistViewModel { Name = p.Name, Duration = p.Duration, Playlist = p }); } IsDataLoaded = true; }
private void ButtonSaveFile_Click(object sender, RoutedEventArgs e) { FileTransfer trans = ((FrameworkElement)sender).DataContext as FileTransfer; if (trans != null) { var library = new MediaLibrary(); library.SavePicture(trans.FileName, trans.Bytes); MessageBox.Show("File saved to 'Saved Pictures'", "File Saved", MessageBoxButton.OK); } }
private Image GetImage() { MediaLibrary ml = new MediaLibrary(); string name = this.Name; Stream s = (from res in ml.Pictures where res.Name == name select res.GetImage()).First(); Image img = new Image() { Source = (ImageSource)PictureDecoder.DecodeJpeg(s, MainPage.PushWidth, MainPage.PushWidth) }; return img; }
/// <summary> /// Reads local media for artists, which are then ordered based on /// the number of tracks and play count of their tracks. Begins /// further processing to find recommendations using MixRadio API. /// </summary> private void FindTopArtists() { Xna.MediaLibrary lib = new Xna.MediaLibrary(); // Get the top artists from the local media library... if (lib.Artists.Count > 0) { Dispatcher.BeginInvoke(() => { this.Note.Text = string.Format("{0} artists on phone...", lib.Artists.Count); }); List <TopArtist> artists = new List <TopArtist>(); foreach (Xna.Artist artist in lib.Artists) { int playCount = 0; try { int count = artist.Songs.Count; foreach (Xna.Song song in artist.Songs) { playCount += song.PlayCount; } int score = count + (playCount * 2); artists.Add(new TopArtist { Name = artist.Name, Score = score }); } catch { } } this._topArtists = (from a in artists orderby a.Score descending select a).ToList <TopArtist>(); Dispatcher.BeginInvoke(() => { this.Loading.Text = string.Format("Found {0} artists, looking for recommendations...", this._topArtists.Count); }); this.ProcessNextArtist(); } else { Dispatcher.BeginInvoke(() => { this.Loading.Visibility = Visibility.Collapsed; this.Note.Visibility = Visibility.Visible; this.Note.Text = "There is no music on the phone, please add some and try again."; }); } }
/// <summary> /// Shuffles the songs of a local artist and starts playback /// </summary> /// <param name="localArtistName">Name of the artist</param> public void ShuffleAndPlayLocalArtist(string localArtistName) { Microsoft.Xna.Framework.Media.MediaLibrary lib = new Microsoft.Xna.Framework.Media.MediaLibrary(); for (int i = 0; i < lib.Artists.Count; i++) { if (localArtistName == lib.Artists[i].Name) { // generate a random track index Random rand = new Random(); int track = rand.Next(0, lib.Artists[i].Songs.Count); Microsoft.Xna.Framework.Media.SongCollection songCollection = lib.Artists[i].Songs; Microsoft.Xna.Framework.Media.MediaPlayer.Play(songCollection, track); Microsoft.Xna.Framework.Media.MediaPlayer.IsShuffled = true; Microsoft.Xna.Framework.FrameworkDispatcher.Update(); break; } } }
/// <param name="quality">0-100 jpg quality</param> /// <returns>Captured picture name</returns> public static Capture CaptureScreenToPictures(int quality = 100) { var sw = System.Diagnostics.Stopwatch.StartNew(); var bmp = CaptureScreen(); string name; long size; Picture pic; using (var ms = new MemoryStream(480 * 800)) { System.Windows.Media.Imaging.Extensions.SaveJpeg(bmp, ms, 480, 800, 0, quality); size = ms.Position; ms.Seek(0, SeekOrigin.Begin); name = string.Format("ScreenDump_{0}", DateTime.Now.ToString("yyyy-mm-dd hh:mm:ss:ffff tt")); pic = new Microsoft.Xna.Framework.Media.MediaLibrary().SavePicture(name, ms); } sw.Stop(); return(new Capture(name, sw.Elapsed, size)); }