我在C#中讀取一個檔案時遇到了一個問題。以下是代碼:
protected override void OnNavigatedTo(NavigationEventArgs EvArgs)
{
base.OnNavigatedTo(EvArgs)。
var Args = EvArgs.Parameter as Windows.ApplicationModel.Activation.IActivatedEventArgs;
var FArgs = Args as Windows.ApplicationModel.Activation.FileActivatedEventArgs。
if (Args != null)
{
if (Args.Kind == Windows.ApplicationModel.Activation.ActivationKind.File)
{
var IMG = new Image()。
IMG.Loaded = IMG_Loaded;
string FP = FArgs.Files[0].Path。
Uri = FP;
IMG.Source = new BitmapImage(new Uri(FP, UriKind.RelativeOrAbsolute))。
FV.Items.Add(IMG)。
PathBlock.Text = FArgs.Files[0].Name " - Ivirius Image Viewer"/span>;
void IMG_Loaded(object sender, RoutedEventArgs e)
{
IMG.Source = new BitmapImage(new Uri(Uri))。
}
}
}
if (Args == null)
{
PathBlock.Text = "Ivirius Image Viewer"/span>;
}
問題出在這一部分:
IMG.Source = new BitmapImage(new Uri(FP, UriKind.RelativeOrAbsolute))。
圖片無法加載,甚至在嘗試了應用程式可以在其自己的檔案中訪問的資源后也是如此:
圖片無法加載。
IMG.Source = new BitmapImage(new Uri("ms-appx://09.png, UriKind.RelativeOrAbsolute))。
它仍然無法作業。 這只適用于以下代碼:
這只適用于以下代碼。
var FOP = new Windows.Storage.Pickers.FileOpenPicker()。
StorageFile F = await FOP.PickSingleFileAsync();
IRandomAccessStream FS = await F.OpenAsync(FileAccessMode.Read)。
var BI = new BitmapImage()。
var IMG = new Image()。
await BI.SetSourceAsync(FS)。
IMG.Source = BI;
遺憾的是,在第一個代碼示例中,我無法使用檔案流或檔案選取器,所以我無法像這里一樣使其作業。
uj5u.com熱心網友回復:
Image.Source = new BitmapImage(); 在UWP中不起作用
問題是檔案Path屬性在UWP平臺上不能直接用來設定影像源。
從你的代碼來看,你似乎用當前的應用程式打開了影像檔案,如果你能從FArgs.Files串列中獲得IStorageItem,你也可以將其轉換為StorageFile,然后將打開的檔案流傳遞給BitmapImage。
更詳細的步驟請參考下面的代碼。
protected async override void OnNavigatedTo(NavigationEventArgs EvArgs)
{
base.OnNavigatedTo(EvArgs)。
var Args = EvArgs.Parameter as Windows.ApplicationModel.Activation.IActivatedEventArgs;
var FArgs = Args as Windows.ApplicationModel.Activation.FileActivatedEventArgs。
if (Args != null)
{
if (Args.Kind == Windows.ApplicationModel.Activation.ActivationKind.File)
{
var IMG = new Image()。
string FP = FArgs.Files[0].Path。
var Uri = FP;
StorageFile imageFile = FArgs.Files[0] as StorageFile;
使用(var stream = await imageFile.OpenReadAsync()
{
var bitmp = new BitmapImage() 。
bitmp.SetSource(stream);
IMG.Loaded = (s, e) => { IMG.Source = bitmp; };
}
RootLayout.Children.Add(IMG)。
}
}
if (Args == null)
{
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/310321.html
標籤:
