简体   繁体   中英

Convert BitmapImage or IRandomAccessStream to byte array in Windows 10 UAP

Who can help me. I don't understand how i can convert BitmapImage or IRandomAccessStream to byte array. I try:

foreach (StorageFile file in files)
{
    BitmapImage src = new BitmapImage();

    using (IRandomAccessStream stream = await file.OpenReadAsync())
    {
        await src.SetSourceAsync(stream);

        WriteableBitmap bitMap = new WriteableBitmap(src.PixelWidth, src.PixelHeight);
        await bitMap.SetSourceAsync(stream);
    }
}

then i have WriteableBitmap and try this:

private byte[] ImageToByeArray(WriteableBitmap wbm)
{
    using (Stream stream = wbm.PixelBuffer.AsStream())
    using (MemoryStream memoryStream = new MemoryStream())
    {
        stream.CopyTo(memoryStream);
        return memoryStream.ToArray();
    }
}

but it's don't work for me ;(

This should do it:

    async Task<byte[]> Convert(IRandomAccessStream s)
    {
        var dr = new DataReader(s.GetInputStreamAt(0));
        var bytes = new byte[s.Size];
        await dr.LoadAsync((uint)s.Size);
        dr.ReadBytes(bytes);
        return bytes;
    }

I used this solution in my WPF applications to save images in database as byte[] . It should also work in your case.

public static byte[] ImageToString(System.Windows.Media.Imaging.BitmapImage img) {
    System.IO.MemoryStream stream = new System.IO.MemoryStream();
    System.Windows.Media.Imaging.BmpBitmapEncoder encoder = new System.Windows.Media.Imaging.BmpBitmapEncoder();
    encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create((System.Windows.Media.Imaging.BitmapSource)img));
    encoder.Save(stream);
    stream.Flush();

    return stream.ToArray();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM