以编程方式设置图像的来源(XAML)

28
我正在开发一个Windows 8应用程序。我需要知道如何通过编程方式设置图像的源。我认为Silverlight的方法可以奏效,但事实并非如此。有谁知道怎么做吗?以下方法不起作用:
string pictureUrl = GetImageUrl();
Image image = new Image();
image.Source = new Windows.UI.Xaml.Media.Imaging.BitmapImage(new Uri(pictureUrl, UriKind.Relative));
image.Stretch = Stretch.None;
image.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Left;
image.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Center;

我收到一个异常,内容为:“给定的 System.Uri 无法转换为 Windows.Foundation.Uri。”

但是,我找不到 Windows.Foundation.Uri 类型。

7个回答

44

我刚尝试过

Image.Source = new BitmapImage(
    new Uri("http://yourdomain.com/image.jpg", UriKind.Absolute));

它可以正常工作...我在这里使用System.Uri。也许你的URI格式不正确,或者你必须使用绝对URI并使用UriKind.Absolute代替?


我也遇到了异常吗? - Arsal

17

这是我使用的代码:

string url = "ms-appx:///Assets/placeHolder.png";
image.Source = RandomAccessStreamReference.CreateFromUri(new Uri(url));

placeHolder.png 的构建操作是什么?我已将其设置为“Content”,但图像无法正确加载。 - Mac
9
我遇到了一个错误,即无法将“RandomAccessStreamReference”转换为“ImageSource”。 - Nick Heiner
2
Image.Source = new BitmapImage( new Uri("ms-appx:///Assets/placeHolder.png", UriKind.Absolute)); 图像.源 = 新的位图图像( 新的统一资源标识符("ms-appx:///Assets/placeHolder.png", 统一资源标识符类型.绝对)); - Rahul K

6
好的,Windows.Foundation.Uri 的文档如下所示:

.NET:这个类型显示为System.Uri。

因此,将它转换为 Windows.Foundation.Uri 并不困难 - 看起来WinRT会为您完成这项工作。问题可能出在您正在使用的URI上。在这种情况下,它是相对于什么的呢?我猜您只需要找到URI的正确格式即可。

5

这个例子使用FileOpenPicker对象获取存储文件。您可以使用任何方法来访问您的文件作为StorageFile对象。

Logo是图像控件的名称。

引用以下代码:

    var fileOpenPicker = new FileOpenPicker();
    fileOpenPicker.ViewMode = PickerViewMode.Thumbnail;
    fileOpenPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
    fileOpenPicker.FileTypeFilter.Add(".png");
    fileOpenPicker.FileTypeFilter.Add(".jpg");
    fileOpenPicker.FileTypeFilter.Add(".jpeg");
    fileOpenPicker.FileTypeFilter.Add(".bmp");

    var storageFile = await fileOpenPicker.PickSingleFileAsync();

    if (storageFile != null)
    {
        // Ensure the stream is disposed once the image is loaded
        using (IRandomAccessStream fileStream = await storageFile.OpenAsync(Windows.Storage.FileAccessMode.Read))
        {
            // Set the image source to the selected bitmap
            BitmapImage bitmapImage = new BitmapImage();

            await bitmapImage.SetSourceAsync(fileStream);
            Logo.Source = bitmapImage;
        }
    }

4

请检查您的pictureUrl,因为它导致了异常。

但这也应该可以正常工作。

img.Source = new BitmapImage(new Uri(pictureUrl, UriKind.Absolute));

这与 Windows.Foundation.Uri 没有任何关系,因为 WinRT 会为您处理它。


3

0
<Image Name="Img" Stretch="UniformToFill" />

var file = await KnownFolders.PicturesLibrary.GetFileAsync("2.jpg");
using(var fileStream = (await file.OpenAsync(Windows.Storage.FileAccessMode.Read))){
     var bitImg= new BitmapImage();
     bitImg.SetSource(fileStream); 
     Img.Source = bitImg;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接