【问题标题】:Converted BitmapImage not displaying on Page转换后的 BitmapImage 不显示在页面上
【发布时间】:2012-07-02 09:58:20
【问题描述】:

我的 Windows Phone 应用程序有问题。当我从 Web 服务获取照片时,我想将其显示为页面上的图像。 Web 服务返回一个 byte[] 作为图像数据。

Dispatcher.BeginInvoke(() =>
{
    tempImage = new BitmapImage();
    globalWrapper = (PhotoWrapper)JsonConvert.DeserializeObject(
                                      response.Content, typeof(PhotoWrapper));
    tempImage.SetSource(new MemoryStream(globalWrapper.PictureBinary, 0,
                                         globalWrapper.PictureBinary.Length));
    globalWrapper.ImageSource = tempImage;
    PictureList.Items.Add(globalWrapper);
});

PictureList 是一个 ListBox 定义为:

<ListBox Name="PictureList" ItemsSource="{Binding}" Margin="0,0,0,0">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <Button Click="details_Click">
                    <Button.Content>
                        <Image Source="{Binding ImageSource}"></Image>
                    </Button.Content>
                 </Button>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

现在,我的问题是,您如何从 web 服务接收一个字节 [] 作为 JSON 并将其显示在页面上?我觉得我离这里很近,但缺少一些相当基本的东西。

【问题讨论】:

    标签: c# image windows-phone-7 xaml rest


    【解决方案1】:

    如果您确定 byte[] 数据有效,则可能与 BitmapUmage 的 CacheOption 属性有关。此属性控制何时将数据从流中实际加载到位图中。默认为 OnDemand,仅在显示图像时从流中加载数据。您可能想尝试使用 OnLoad 选项,它会立即加载它,从而允许您关闭流。

    Dispatcher.BeginInvoke(() =>
    {
        globalWrapper = (PhotoWrapper)JsonConvert.DeserializeObject(
                                          response.Content, typeof(PhotoWrapper));
        tempImage = new BitmapImage();
        tempImage.BeginInit();
        tempImage.CacheOption = BitmapCacheOption.OnLoad;
        tempImage.SetSource(new MemoryStream(globalWrapper.PictureBinary, 0,
                                             globalWrapper.PictureBinary.Length));
        tempImage.EndInit();
        globalWrapper.ImageSource = tempImage;
        PictureList.Items.Add(globalWrapper);
    });
    

    【讨论】:

    • 我确实找到了错误,这是因为 byte[] 由于某种原因没有被放入内存流中。标记为答案,因为“如果你确定..”让我回去检查。在你开始发展之前,你永远不会真正理解“这是生活中的小事”这句话......
    猜你喜欢
    • 2018-02-16
    • 2020-08-06
    • 1970-01-01
    • 1970-01-01
    • 2017-11-11
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 2015-02-12
    相关资源
    最近更新 更多