How to turn Windows.UI.Xaml.Media.Imaging.BitmapImage into byte[]

水 知 105 Reputation points
2023-10-23T02:55:26.6866667+00:00

Things are like this:

I have read a image file and I decoded it to show it in an Image(img).

Then I got the value of img.Source.

I want to save it into an database but at first I should turn the BitmapImage into byte[]. I've searched tens of articles but their answers are unusable since their BitmapImage is System.Windows.Media.Imaging.BitmapImage, not Windows.UI.Xaml.Media.Imaging.BitmapImage. I can't using System.Windows.Media cause seems there's no such a namespace in UWP.

Thus I can't use BitmapImage.StreamSource. Please help, thanks a lot!

Universal Windows Platform (UWP)
0 comments No comments
{count} votes

Accepted answer
  1. Junjie Zhu - MSFT 16,701 Reputation points Microsoft Vendor
    2023-10-23T03:53:13.89+00:00

    Hi @水 知 ,

    Welcome to Micrsoft Q&A!

    It is recommended that you use RandomAccessStreamReference.CreateFromUri(Uri) to access BitmapImage.

    The name of my image control is Testimg.

    You can refer to the following code sample, hope it helps!

    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"/>
    

    Thank you.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful