0

I am trying to change pixels from a Softwarebitmap.

I want to know if there is an equivalent for Bitmap.Get/SetPixel(x,y,color) in Softwarebitmap UWP.

slavoo
  • 5,798
  • 64
  • 37
  • 39

1 Answers1

0

If you want to read and write softwareBitmap that you should use unsafe code.

To use softwareBitmap is hard that you should write some code.

First using some code.

using System.Runtime.InteropServices;

Then create an interface

[ComImport]
[Guid("5B0D3235-4DBA-4D44-865E-8F1D0E4FD04D")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
unsafe interface IMemoryBufferByteAccess
{
    void GetBuffer(out byte* buffer, out uint capacity);
}

You can use this code to change the pixel.

Creating the soft bitmap.

        var softwareBitmap = new SoftwareBitmap(BitmapPixelFormat.Bgra8, 100, 100, BitmapAlphaMode.Straight);

Writing pixel.

         using (var buffer = softwareBitmap.LockBuffer(BitmapBufferAccessMode.ReadWrite))
        {
            using (var reference = buffer.CreateReference())
            {
                unsafe
                {
                    ((IMemoryBufferByteAccess) reference).GetBuffer(out var dataInBytes, out _);

                    // Fill-in the BGRA plane
                    BitmapPlaneDescription bufferLayout = buffer.GetPlaneDescription(0);
                    for (int i = 0; i < bufferLayout.Height; i++)
                    {
                        for (int j = 0; j < bufferLayout.Width; j++)
                        {
                            byte value = (byte) ((float) j / bufferLayout.Width * 255);
                            dataInBytes[bufferLayout.StartIndex + bufferLayout.Stride * i + 4 * j + 0] = value; // B
                            dataInBytes[bufferLayout.StartIndex + bufferLayout.Stride * i + 4 * j + 1] = value; // G
                            dataInBytes[bufferLayout.StartIndex + bufferLayout.Stride * i + 4 * j + 2] = value; // R
                            dataInBytes[bufferLayout.StartIndex + bufferLayout.Stride * i + 4 * j + 3] = (byte) 255; // A
                        }
                    }
                }
            }
        }

You can write the pixel for write the dataInBytes and you should use byte.

For the pixel is BGRA and you should write this byte.

If you want to show it, you need to Convert when the BitmapPixelFormat isnt Bgra8 and the BitmapAlphaMode is Straight and you can use this code.

        if (softwareBitmap.BitmapPixelFormat != BitmapPixelFormat.Bgra8 ||
            softwareBitmap.BitmapAlphaMode == BitmapAlphaMode.Straight)
        {
            softwareBitmap = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);
        }

This code can show it to Image.

        var source = new SoftwareBitmapSource();
        await source.SetBitmapAsync(softwareBitmap);
        Image.Source = source;

See: Create, edit, and save bitmap images - UWP app developer

lindexi
  • 4,182
  • 3
  • 19
  • 65