如何从另一个SoftwareBitmap(UWP)

时间:2018-03-12 21:23:54

标签: c# windows uwp windows-10-universal windows-10-iot-core

使用另一个Windows.Graphics.Imaging.SoftwareBitmap对象(深层副本)的区域副本(例如BitmapBounds)创建新SoftwareBitmap对象的最有效(最简单)方法是什么? Windows UWP应用程序?

SoftwareBitmap没有这样的构造函数或静态方法。所有Copy *方法都复制整个位图。

我使用WriteableBitmap来实现这一目标:

    SoftwareBitmap CreateFromBitmap(SoftwareBitmap bmp, Rect rect)
    {
        WriteableBitmap wbmpIn = new WriteableBitmap(bmp.PixelWidth, bmp.PixelHeight);
        bmp.CopyToBuffer(wbmpIn.PixelBuffer);

        WriteableBitmap wbmpOut = new WriteableBitmap((int)rect.Width, (int)rect.Height);
        wbmpOut.Blit(new Rect(0, 0, rect.Width, rect.Height), wbmpIn, rect);

        SoftwareBitmap ret = new SoftwareBitmap(bmp.BitmapPixelFormat, (int)rect.Width, (int)rect.Height);
        ret.CopyFromBuffer(wbmpOut.PixelBuffer);

        return ret;
    }

但它看起来并不有效 - 涉及两个CopyFromBuffer()和一个Blit()。

是否有更有效的解决方案?

1 个答案:

答案 0 :(得分:0)

您可以参考以下代码,它可以从现有的SoftwareBitmap创建一个新的裁剪的SoftwareBitmap。

    private async Task<SoftwareBitmap> CreateFromBitmap(SoftwareBitmap softwareBitmap, Rect rect)
    {
        using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
        {
            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, stream);

            encoder.SetSoftwareBitmap(softwareBitmap);

            encoder.BitmapTransform.Bounds = new BitmapBounds()
            {
                X = (uint)rect.X,
                Y = (uint)rect.Y,
                Height = (uint)rect.Height,
                Width = (uint)rect.Width
            };

            await encoder.FlushAsync();

            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);

            return await decoder.GetSoftwareBitmapAsync(softwareBitmap.BitmapPixelFormat, softwareBitmap.BitmapAlphaMode);
        }
    }



    var croppedBitmap = await CreateFromBitmap(sourceSoftwareBmp, new Rect(0, 0, 200, 100));

enter image description here