How save BitmapImage WinRT

前端 未结 5 884
攒了一身酷
攒了一身酷 2020-12-21 06:20

I have BitmapImage:

BitmapImage image = new BitmapImage();
image.SetSource(memStream);

I want to save the image to the disk to see in the f

5条回答
  •  [愿得一人]
    2020-12-21 07:14

    Here's a code I found sometime ago in the web. I'm not sure, but if I rember right it was from the sdk samples or a winrt blog

    It all comes down to the WritabelBitmap Image ( like the other already posted), create a decoder and push it to the stream.

      /// 
            /// 
            /// 
            /// 
            /// 
            /// 
            /// 
            public static async Task SaveToFile(
                this WriteableBitmap writeableBitmap,
                IStorageFile outputFile,
                Guid encoderId)
            {
                try
                {
                    Stream stream = writeableBitmap.PixelBuffer.AsStream();
                    byte[] pixels = new byte[(uint)stream.Length];
                    await stream.ReadAsync(pixels, 0, pixels.Length);
    
                    using (var writeStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        var encoder = await BitmapEncoder.CreateAsync(encoderId, writeStream);
                        encoder.SetPixelData(
                            BitmapPixelFormat.Bgra8,
                            BitmapAlphaMode.Premultiplied,
                            (uint)writeableBitmap.PixelWidth,
                            (uint)writeableBitmap.PixelHeight,
                            96,
                            96,
                            pixels);
                        await encoder.FlushAsync();
    
                        using (var outputStream = writeStream.GetOutputStreamAt(0))
                        {
                            await outputStream.FlushAsync();
                        }
                    }
                }
                catch (Exception ex)
                {
                    string s = ex.ToString();
                }
            }
    

提交回复
热议问题