在WinRT中加载图像文件

时间:2014-05-21 07:11:37

标签: c# windows-runtime comexception

我有一个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.s回答,我尝试了其他一些功能。以下给出了同样的错误:

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

然而(显然,提供我提供音乐功能)这不是:

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

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

3 个答案:

答案 0 :(得分: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更改为测试图像的位置。

答案 1 :(得分: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。没有看到任何错误。可能是别的吗?

答案 2 :(得分: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
    }
}