如何将Windows.UI.Xaml.Media.Imaging.BitmapImage 转换为 byte[]

Roy Li - MSFT 32,466 信誉分 Microsoft 供应商
2024-04-30T01:44:38.4866667+00:00

事情是这样的:

我已经读取了一个图像文件,并对其进行了解码以将其显示在 Image(img) 中。

然后我得到了 img 的值。源。

我想将其保存到数据库中,但首先我应该将 BitmapImage 转换为 byte[]。我已经搜索了数十篇文章,但它们的答案无法使用,因为它们的 BitmapImage 是 System.Windows.Media.Imaging.BitmapImage,而不是 Windows.UI.Xaml.Media.Imaging.BitmapImage。我无法使用 System.Windows.Media,因为 UWP 中似乎没有这样的命名空间。 因此,我不能使用 BitmapImage.StreamSource。

非常感谢!

此问题由How to turn Windows.UI.Xaml.Media.Imaging.BitmapImage into byte[] - Microsoft Q&A总结而来.

通用 Windows 平台 (UWP)
通用 Windows 平台 (UWP)
一个 Microsoft 平台,用于生成和发布适用于 Windows 桌面设备的应用。
27 个问题
0 个注释 无注释
{count} 票

1 个答案

排序依据: 非常有帮助
  1. Junjie Zhu - MSFT 15,676 信誉分 Microsoft 供应商
    2024-04-30T07:03:25.15+00:00

    你好!

    建议使用 RandomAccessStreamReference.CreateFromUri(Uri) 访问 BitmapImage。

    我的图像控件的名称是 Testimg

    可以参考下面的代码示例,希望对您有所帮助!

    private void Image_Loaded(object sender, RoutedEventArgs e)
    {
        Image img = sender as Image;
        BitmapImage bitmapImage = new BitmapImage();
        img.Width = bitmapImage.DecodePixelWidth = 80; //natural px width of image source
                                                        // don't need to set Height, system maintains aspect ratio, and calculates the other
                                                        // dimension, so long as one dimension measurement is provided
        bitmapImage.UriSource = new Uri(img.BaseUri, "Assets/StoreLogo.png");
        img.Source = bitmapImage;
    }
    private async void Button_Click(object sender, RoutedEventArgs e)
    {
                
        BitmapImage bitmapImage= Testimg.Source as BitmapImage;
        RandomAccessStreamReference stream = RandomAccessStreamReference.CreateFromUri(bitmapImage.UriSource);
        var streamContent = await stream.OpenReadAsync();
        byte[] buffer = new byte[streamContent.Size];
        await streamContent.ReadAsync(buffer.AsBuffer(), (uint)streamContent.Size, InputStreamOptions.None);
              
    }
    
    
    
    <Image x:Name="Testimg" Loaded="Image_Loaded"  HorizontalAlignment="Left" Height="100" VerticalAlignment="Top" Width="100"/>
    

    谢谢。


    如果答案是正确的,请点击“接受答案”并点赞。 如果您对此答案还有其他疑问,请点击“评论”。 注意:如果您想接收电子邮件通知,请按照我们的文档中的步骤启用电子邮件通知 此线程的相关电子邮件通知。

    0 个注释 无注释