如何将IImageProvider编码为PNG图像?

时间:2015-03-09 13:10:22

标签: windows-phone-8.1 png windows-8.1 win-universal-app lumia-imaging-sdk

假设我有一个LumiaImagingSDK渲染链设置,我想渲染一个最终的IImageProvider对象,如何将其编码为PNG图像?

1 个答案:

答案 0 :(得分:1)

Lumia Imaging SDK支持PNG图像作为输入,但是没有" PNG渲染器"在SDK中可用。

幸运的是,如果您正在开发Windows 8.1(StoreApplication /通用应用程序/ Windows Phone 8.1项目),可以使用Windows编码器(Windows.Graphics.Imaging.BitmapEncoder)。

假设您要渲染的IImageProvider被称为" source"这是一个代码段,您可以使用它将结果图像编码为PNG:

using Lumia.Imaging;
using Windows.Graphics.Imaging;
using System.IO;

...

using (var renderer = new BitmapRenderer(source, ColorMode.Bgra8888))
{
    var bitmap = await renderer.RenderAsync();
    byte[] pixelBuffer = bitmap.Buffers[0].Buffer.ToArray();


    using (var stream = new InMemoryRandomAccessStream())
    {
        var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream).AsTask().ConfigureAwait(false);
        encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)bitmap.Dimensions.Width, (uint)bitmap.Dimensions.Height, 96, 96, pixelBuffer);
        await encoder.FlushAsync().AsTask().ConfigureAwait(false);

       //If InMemoryRandomAccessStream (IRandomAccessStream) works for you, end here.
       //If you need an IBuffer, here is how you get one:

        using (var memoryStream = new MemoryStream())
        {
            memoryStream.Capacity = (int)stream.Size;
            var ibuffer = memoryStream.GetWindowsRuntimeBuffer();
            await stream.ReadAsync(ibuffer, (uint)stream.Size, InputStreamOptions.None).AsTask().ConfigureAwait(false);
        }
    }
}

这将根据您的需要为您提供InMemoryRandomAccessStreamIRandomAccessStream)或IBuffer内存中的字节数。然后,您可以将缓冲区保存到磁盘或将其传递给应用程序的其他部分。