将字节数组或文件存储转换为位图图像

时间:2012-12-08 14:27:03

标签: c# windows windows-8

我选择文件到存储文件后,如何将此文件转换为图像,以便将其显示为个人资料图片?
我将文件转换为字节数组,但不知道下一步该做什么或有另一种方法?

这是我的代码:

var openPicker = new Windows.Storage.Pickers.FileOpenPicker();
openPicker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
openPicker.FileTypeFilter.Add(".png");
openPicker.FileTypeFilter.Add(".Jpeg");
openPicker.FileTypeFilter.Add(".Jpg");
StorageFile file = await openPicker.PickSingleFileAsync();

var stream = await file.OpenReadAsync();

using (var dataReader = new DataReader(stream))
  {
      var  bytes = new byte[stream.Size];
      await dataReader.LoadAsync((uint)stream.Size);
      dataReader.ReadBytes(bytes);
      var stream2 = new MemoryStream(bytes);
  }

1 个答案:

答案 0 :(得分:4)

下面的代码将字节转换为BitmapImage

BitmapImage image1 = new BitmapImage();
InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream();
ms.WriteAsync(tBytes.AsBuffer());
ms.FlushAsync().AsTask().Wait();
ms.Seek(0);
image1.SetSource(ms);
image.Source = image1;


我从某个地方得到了这个,如果有帮助就试试这个

FileOpenPicker openPicker = new FileOpenPicker();
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".cmp");
openPicker.FileTypeFilter.Add(".png");
openPicker.FileTypeFilter.Add(".tif");
openPicker.FileTypeFilter.Add(".gif");
openPicker.FileTypeFilter.Add(".bmp");
StorageFile file = await openPicker.PickSingleFileAsync();
IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read);
BitmapImage bmp = new BitmapImage();
bmp.SetSource(stream);
Image1.Source = bmp;