Speichern von Bildern unter WP8
Manchmal möchte man in seiner Windows Phone 8 Anwendung ein paar Bilder aus dem Internet anzeigen, doch aus Datenvolumen-Schutz wäre es doch schön, wenn man die Bilder einfach runterlädt und diese nicht ständig aus dem Web bezogen werden. In diesem Blog-Beitrag möchte ich euch nun zeigen, wie ihr ganz einfach ein Bild aus dem Internet in dem IsolatedStorage speichern könnt und natürlich wieder laden könnt. Als Vorbereitung gehe ich davon aus, dass das Foto bereits im JPEG-Format vorliegt, da dies das einzige Format ist, welches standardmäßig zur Verfügung steht.
Zum Abspeichern verwendet ihr einfach die folgende Methode SaveImageToIsolatedStorage, welche den Pfad zum Web-Bild als Parameter hat und das Bild unter dem Namen test.jpg im IsolatedStorage abspeichert und euch den lokalen Pfad als Rückgabe liefert.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
public string SaveImageToIsolatedStorage(string remoteImgPath) { string localImgPath = "test.jpg"; WebClient client = new WebClient(); client.OpenReadCompleted += (s, e) => { if (e.Error == null) { using (var storage = IsolatedStorageFile.GetUserStoreForApplication()) { var bi = new BitmapImage(); bi.SetSource(e.Result); var wb = new WriteableBitmap(bi); using (var isoFileStream = storage.CreateFile(localImgPath)) { var width = wb.PixelWidth; var height = wb.PixelHeight; Extensions.SaveJpeg(wb, isoFileStream, width, height, 0, 100); } } } else { MessageBox.Show(String.Format("Leider ist ein Fehler aufgetreten: {0}", e.Error.Message), "Fehler", MessageBoxButton.OK); } }; client.OpenReadAsync(new Uri(remoteImgPath, UriKind.Absolute)); return localImgPath; } |
Zum Laden verwendet ihr analog die Methode LoadImageFromIsolatedStorage, welche den lokalen Pfad zum Bild als Parameter bekommt und ein BitmapImage mit dem Bild zurückliefert.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public BitmapImage LoadImageFromIsolatedStorage(string imgPath) { BitmapImage bi = new BitmapImage(); using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) { using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(imgPath, FileMode.Open, FileAccess.Read)) { bi.SetSource(fileStream); } } return bi; } |