Android Code Snippet [B4X] [BitmapCreator] Find Minimum Bounding Rectangle

Discussion in 'Code Snippets' started by Erel, Jul 5, 2018.

  1. Erel

    Erel Administrator Staff Member Licensed User

    Input: A Bitmap or B4XBitmap.

    Output: A rectangle with the boundaries of the non-transparent area.

    Code:
    Sub FindMinRect (bmp As B4XBitmap) As B4XRect
       
    Dim bc As BitmapCreator
       bc.Initialize(bmp.Width, bmp.Height)
       bc.CopyPixelsFromBitmap(bmp)
       
    Dim r As B4XRect
       r.Initialize(bc.mWidth / 
    2, -1, bc.mWidth / 20)
       
    For y = 0 To bc.mHeight - 1
           
    For x = 0 To bc.mWidth - 1
               
    If bc.IsTransparent(x, y) = False Then
                   r.Left = 
    Min(r.Left, x)
                   
    Exit
               
    End If
           
    Next
           
    If x < bc.mWidth Then
               
    If r.Top = -1 Then
                   r.Top = y
               
    Else
                   r.Bottom = y + 
    1
               
    End If
               
    For x = bc.mWidth - 1 To 0 Step -1
                   
    If bc.IsTransparent(x, y) = False Then
                       r.Right = 
    Max(r.Right, x + 1)
                       
    Exit
                   
    End If
               
    Next
           
    End If
       
    Next
       
    Return r
    End Sub
    Usage:
    Code:
    Dim r As B4XRect = FindMinRect(bmp)
    ImageView2.SetBitmap(bmp.Crop(r.Left, r.Top, r.Width, r.Height))
    Depends on: XUI and BitmapCreator libraries.
     
    Last edited: Jul 8, 2018
  2. asales

    asales Well-Known Member Licensed User

    I don't understand what this function do.
    I tried to use it, but I don't saw an image in output.
    Can you put an image of output to ilustrate?
     
    Peter Simpson likes this.
  3. Erel

    Erel Administrator Staff Member Licensed User

    1. I've updated the code. There was a bug in the previous code.

    2. See this screenshot:

    [​IMG]

    The top ImageView shows the original image. The bottom ImageView shows the cropped image based on this code.
     
    Gunther, angel_, asales and 1 other person like this.
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