在WinRT中加载图像文件
本文关键字:图像 文件 加载 WinRT | 更新日期: 2023-09-27 18:04:16
我有一个WinRT项目,在尝试预览图像时出错。我已经设置了允许访问图片库的功能,并且正在使用以下代码:
var file = await Windows.Storage.KnownFolders.PicturesLibrary.GetFileAsync(path);
var fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
var img = new BitmapImage();
img.SetSource(fileStream);
此错误发生在第一行:
A first chance exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll
Additional information: Error HRESULT E_FAIL has been returned from a call to a COM component.
我已经尝试过其他操作,例如folder.GetFilesAsync()
,但出现了相同的错误。我是否需要另一种或功能来允许此功能正常工作?
编辑:
根据@L.T.的回答,我尝试了一些其他功能。下面给了我同样的错误:
var folder = KnownFolders.PicturesLibrary;
var files = await folder.GetFilesAsync();
然而(显然,如果我提供音乐功能(这并不是:
var testfolder = KnownFolders.MusicLibrary;
var files = await testfolder.GetFilesAsync();
我不怀疑这是我的图片库特有的东西,但我不知道这可能是什么。
如果您的成本只是预览图像。你可以使用这个
Uri uri = new Uri("ms-appx:///Assets/test.png");
BitmapImage bitmap = new BitmapImage(uri);
Image image = new Image();
image.Source = bitmap;
并将图像添加到画布中。但是您需要先将test.png添加到项目资产中,或者您可以将Uri更改为测试映像的位置。
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Image Name="img"></Image>
<Button Name="btn" Click="Btn_OnClick"></Button>
</Grid>
private async void Btn_OnClick(object sender, RoutedEventArgs e)
{
var file = await Windows.Storage.KnownFolders.PicturesLibrary.GetFileAsync("images.jpg");
var fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
var image = new BitmapImage();
image.SetSource(fileStream);
img.Source = image;
}
我有windows8.1和vs.2013。没有看到任何错误。可能是别的什么?
//////to load an image file just do this
//put this in your app.xaml
protected override void OnActivated(IActivatedEventArgs args)
{
var root = Window.Current.Content as Frame;
var mainPage = root.Content as MainPage;
if (mainPage != null && args is FileOpenPickerContinuationEventArgs)
{
mainPage.ContinueFileOpenPicker(args as FileOpenPickerContinuationEventArgs);
}
}
//and this in your btn event
private void Button_Click(object sender, RoutedEventArgs e)
{
var openPicker = new FileOpenPicker
{
ViewMode = PickerViewMode.Thumbnail,
SuggestedStartLocation = PickerLocationId.PicturesLibrary
};
openPicker.FileTypeFilter.Add(".jpg");
openPicker.PickSingleFileAndContinue();
}
//and this in you page
public void ContinueFileOpenPicker(FileOpenPickerContinuationEventArgs fileOpenPickerContinuationEventArgs)
{
if (fileOpenPickerContinuationEventArgs.Files != null)
{
// Do something with selected file/s
}
}