3

我有一个 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()出现相同的错误。我是否需要其他功能才能使此功能正常工作?

编辑:

基于@LTs 的回答,我尝试了其他一些功能。以下给了我同样的错误:

var folder = KnownFolders.PicturesLibrary;            
var files = await folder.GetFilesAsync();

但是(显然,如果我提供音乐功能)这不会:

var testfolder = KnownFolders.MusicLibrary;
var files = await testfolder.GetFilesAsync();

我不怀疑这是我的图片库特有的东西,但我不知道那可能是什么。

4

3 回答 3

2

如果您的成本只是预览图像。你可以用这个

        Uri uri = new Uri("ms-appx:///Assets/test.png");
        BitmapImage bitmap = new BitmapImage(uri);
        Image image = new Image();
        image.Source = bitmap;

并将图像添加到画布。但是您需要先将 test.png 添加到您的项目资产中,或者您可以将 Uri 更改为测试图像的位置。

于 2014-05-28T06:23:04.877 回答
0
   <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。看不到任何错误。可能是别的东西?

于 2014-06-03T04:21:23.580 回答
0
    //////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
    }
}
于 2014-11-15T19:39:44.567 回答