B4J Code Snippet Get Image Pixels

B4X:
Sub GetPixels (img As Image) As Byte()
   Dim jo As JavaObject = img
   Dim reader As JavaObject = jo.RunMethod("getPixelReader", Null)
   Dim buffer(img.Width * img.Height * 4) As Byte
   Dim PixelFormat As JavaObject
   PixelFormat.InitializeStatic("javafx.scene.image.PixelFormat")
   Dim width = img.Width, height = img.Height As Int
   reader.RunMethod("getPixels", Array(0, 0, width, height, PixelFormat.RunMethod("getByteBgraInstance", Null), _
       buffer, 0, width * 4))
   Return buffer
End Sub

Usage example:
B4X:
    Dim img As Image = fx.LoadImage(File.DirAssets, "smiley.png")
   Dim buffer() As Byte = GetPixels(img)
   Dim width As Int = img.Width
   Dim height As Int = img.Height
   For x = 0 To width - 1
       For y = 0 To height - 1
           Dim i As Int = y * width * 4 + x * 4
           Dim b As Int = Bit.And(0xFF, buffer(i))
           Dim g As Int = Bit.And(0xFF, buffer(i + 1))
           Dim r As Int = Bit.And(0xFF, buffer(i + 2))
           Dim a As Int = Bit.And(0xFF, buffer(i + 3))
           Log($"${a}, ${r}, ${g}, ${b}"$)
       Next
   Next

Depends on JavaObject.
 

Robert Valentino

Well-Known Member
Licensed User
Longtime User
Is there a SetPixels version so I can change some of the pixels and write the image back to a new file
 
Top