標籤:
1. 開啟圖片檔案並轉換為BitmapImage類
首先要做的自然是開啟一個圖片檔案了,可以使用FileOpenPicker來手動選擇圖片,總之能拿到一個StorageFile都行。
//開啟圖片選取器,選擇要發送的圖片var openPicker = new FileOpenPicker{ ViewMode = PickerViewMode.Thumbnail, SuggestedStartLocation = PickerLocationId.PicturesLibrary};openPicker.FileTypeFilter.Add(".jpg");openPicker.FileTypeFilter.Add(".jpeg");var file = await openPicker.PickSingleFileAsync();
也可以使用StorageFile.GetFileFromApplicationUriAsync擷取,下面代碼得到的檔案是應用隔離儲存區 (Isolated Storage)檔案夾LocalState裡的1.jpg檔案。
var path = "ms-appdata:///local/1.jpg";var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(path));
接下來將檔案開啟,並把檔案流寫入到BitmapImage中。
//將圖片檔案讀取為BitmapImagevar fileStream = await file.OpenReadAsync();var bitmap = new BitmapImage();await bitmap.SetSourceAsync(fileStream);
2. 將圖片byte[]資訊轉換為bitmap
首先要把byte[]轉換為IRandomAccessStream然後再使用BitmapImage.SetSourceAsync方法將流寫入bitmap中,單純的MemoryStream是不能直接寫入到bitmap中的。
public async static Task<BitmapImage> ConvertBytesToBitmapImage(byte[] bytes){ try { if (bytes == null || bytes.Length == 0) return null; var stream = new MemoryStream(bytes); var randomAccessStream = new InMemoryRandomAccessStream(); using (var outputStream = randomAccessStream.GetOutputStreamAt(0)) { var dw = new DataWriter(outputStream); var task = new Task(() => dw.WriteBytes(stream.ToArray())); task.Start(); await task; await dw.StoreAsync(); await outputStream.FlushAsync(); var bitmapImage = new BitmapImage(); await bitmapImage.SetSourceAsync(iRandomAccessStream); return bitmapImage; } } catch (Exception exception) { Debug.WriteLine("[Error] Convert bytes to BitmapImage failed,exception:{0}", exception); return null; }}
Universal App圖片檔案和圖片byte[]資訊轉換為bitmap