如何有效调整图像的亮度

时间:2019-01-10 14:49:07

标签: c# uwp writeablebitmap

有人知道UWP在运行时调整图像亮度的更有效方法吗?

我发现this question可以正常工作,但运行速度非常慢。 但是,我在网上找不到任何文档表明存在另一种方法。

这是我有问题的代码。

// TODO Make Image Brightness Slider quicker and more intuitive. 
private WriteableBitmap ChangeBrightness(WriteableBitmap source, int increment)
{
    var dest = new WriteableBitmap(source.PixelWidth, source.PixelHeight);

    byte[] color = new byte[4];

    using (var srcBuffer = source.PixelBuffer.AsStream())
    using (var dstBuffer = dest.PixelBuffer.AsStream())
    {
        while (srcBuffer.Read(color, 0, 4) > 0)
        {
            for (int i = 0; i < 3; i++)
            {
                var value = (float)color[i];
                var alpha = color[3] / (float)255;
                value /= alpha;
                value += increment;
                value *= alpha;

                if (value > 255)
                {
                    value = 255;
                }

                color[i] = (byte)value;
            }

            dstBuffer.Write(color, 0, 4);
        }
    }

    return dest;
}

1 个答案:

答案 0 :(得分:1)

这可能有效。我没有测试:

    private async Task<WriteableBitmap> ChangeBrightness(WriteableBitmap source, float increment)
    {
        var canvasBitmap = CanvasBitmap.CreateFromBytes(CanvasDevice.GetSharedDevice(), source.PixelBuffer,
            source.PixelWidth, source.PixelHeight, DirectXPixelFormat.B8G8R8A8UIntNormalized);

        var brightnessFx = new BrightnessEffect
        {
            Source = canvasBitmap,
            BlackPoint = new Vector2(0, increment)
        };

        var crt = new CanvasRenderTarget(CanvasDevice.GetSharedDevice(), source.PixelWidth, source.PixelHeight, 96);

        using (var ds = crt.CreateDrawingSession())
        {
            ds.DrawImage(brightnessFx);
        }

        crt.GetPixelBytes(source.PixelBuffer);

        return source;
    }

您必须引用win2d nuget