Universal App图片文件和图片byte[]信息转换为bitmap
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获取,下面代码得到的文件是应用独立存储文件夹LocalState里的1.jpg文件。
var path = "ms-appdata:///local/1.jpg"; var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(path));
接下来将文件打开,并把文件流写入到BitmapImage中。
//将图片文件读取为BitmapImage var 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; } }