B4J Code Snippet Get Image Pixels

Discussion in 'B4J Code Snippets' started by Erel, Apr 9, 2018.

  1. Erel

    Erel Administrator Staff Member Licensed User

    Code:
    Sub GetPixels (img As ImageAs Byte()
       
    Dim jo As JavaObject = img
       
    Dim reader As JavaObject = jo.RunMethod("getPixelReader"Null)
       
    Dim buffer(img.Width * img.Height * 4As Byte
       
    Dim PixelFormat As JavaObject
       PixelFormat.InitializeStatic(
    "javafx.scene.image.PixelFormat")
       
    Dim width = img.Width, height = img.Height As Int
       reader.RunMethod(
    "getPixels"Array(00, width, height, PixelFormat.RunMethod("getByteBgraInstance"Null), _
           buffer, 
    0, width * 4))
       
    Return buffer
    End Sub
    Usage example:
    Code:
    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.
     
  2. Robert Valentino

    Robert Valentino Well-Known Member Licensed User

    Is there a SetPixels version so I can change some of the pixels and write the image back to a new file
     
  3. Erel

    Erel Administrator Staff Member Licensed User

Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice