Saturday, June 1, 2019

Sizing WriteableBitmap using VB

I needed to size a WriteableBitmap in UWP VB according to the scale of my app because of the necessities of Drag-and-Drop. It took a bit to figure out, mostly because of the dearth of examples in vb and pretty much everything I came across is too old and in c-sharp or javascript or is germaine to WPF or Classic Apps only. UWP is different. Finally, I put together an encoder-based thing to do that.

I thought it would be useful for those who need to scale WriteableBitmaps in Visual Basic using UWP to have a function that does this stuff. ((As if searches for this very subject would lead here. In reality this does not exist.))  If you're not used to BitmapEncoders, like me, they may seem kind of complicated. For instance you don't collect the data, it waits in the object to be plugged into something using a third party object after the work is done. But it works.

You have to include Windows.Graphics.Imaging namespace.

Code 6-1-2019:

Private Async Function WBToSizedWB(wbIn As WriteableBitmap, scaleX As Single, scaleY As Single) As Task(Of WriteableBitmap)
        Dim MemoryStream1 = New InMemoryRandomAccessStream
        Dim Encoder1 As BitmapEncoder = Await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, MemoryStream1)
        Dim bt2() As Byte
        Dim PixelStream1 As Stream = wbIn.PixelBuffer.AsStream
        Dim outPWidth, outPHeight As Integer

        outPWidth = scaleX * wbIn.PixelWidth
        outPHeight = scaleY * wbIn.PixelHeight
        ReDim bt2(PixelStream1.Length - 1)
        Await PixelStream1.ReadAsync(bt2, 0, PixelStream1.Length)
        Encoder1.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, wbIn.PixelWidth, wbIn.PixelHeight, 75, 75, bt2)
        Encoder1.BitmapTransform.ScaledHeight = outPHeight
        Encoder1.BitmapTransform.ScaledWidth = outPWidth
        Await Encoder1.FlushAsync
        Dim wb1 As WriteableBitmap = New WriteableBitmap(3, 3)
        Await wb1.SetSourceAsync(MemoryStream1)
        Return wb1

    End Function

Private Function WritableBitmapToSoftwareBitmap(wbIN As WriteableBitmap) As SoftwareBitmap
        Dim SoftwareBitmap1 As SoftwareBitmap = New SoftwareBitmap(BitmapPixelFormat.Bgra8, wbIN.PixelWidth, wbIN.PixelHeight)

        SoftwareBitmap1.CopyFromBuffer(wbIN.PixelBuffer)
        Return SoftwareBitmap1

    End Function

Felix the Cat 1914