Android Code Snippet [B4X] Convert bitmap to BMP format

Discussion in 'Code Snippets' started by Erel, Jun 24, 2018.

  1. Erel

    Erel Administrator Staff Member Licensed User

    Input: B4XBitmap / Bitmap / Image
    Output: array of bytes with the BMP format

    Depends: XUI, BitmapCreator, RandomAccessFile (all internal libraries)

    Code:
    Sub BitmapToBMP (img As B4XBitmap) As Byte()
       
    Dim Padding As Int = 4 - ((img.Width * 3Mod 4)
       
    If Padding = 4 Then Padding = 0
       
    Dim HeaderSize As Int = 40
       
    Dim offset As Int = HeaderSize + 14
       
    Dim size As Int = offset + img.Width * img.Height * 3 + img.Height * Padding
       
    Dim raf As RandomAccessFile
       
    Dim buffer(size) As Byte
       raf.Initialize3(buffer, 
    True)
       raf.WriteBytes(
    Array As Byte(Asc("B"), Asc("M")), 02, raf.CurrentPosition)
       raf.WriteInt(size, raf.CurrentPosition)
       raf.CurrentPosition = raf.CurrentPosition + 
    4
       raf.WriteInt(offset, raf.CurrentPosition)
       
       raf.WriteInt(HeaderSize, raf.CurrentPosition)
       raf.WriteInt(img.Width, raf.CurrentPosition)
       raf.WriteInt(img.Height, raf.CurrentPosition)
       raf.WriteShort(
    1, raf.CurrentPosition)
       raf.WriteShort(
    24, raf.CurrentPosition)
       raf.WriteInt(
    0, raf.CurrentPosition)
       raf.WriteInt(
    0, raf.CurrentPosition)
       raf.WriteInt(
    0, raf.CurrentPosition)
       raf.WriteInt(
    0, raf.CurrentPosition)
       raf.WriteInt(
    0, raf.CurrentPosition)
       raf.WriteInt(
    0, raf.CurrentPosition)
       
    Dim bc As BitmapCreator
       bc.Initialize(img.Width, img.Height)
       bc.CopyPixelsFromBitmap(img)
       
    Dim a As ARGBColor
       
    For y = bc.mHeight - 1 To 0 Step -1
           
    For x = 0 To bc.mWidth - 1
               bc.GetARGB(x, y, a)
               raf.WriteByte(a.b, raf.CurrentPosition)
               raf.WriteByte(a.g, raf.CurrentPosition)
               raf.WriteByte(a.r, raf.CurrentPosition)
           
    Next
           
    For i = 0 To Padding - 1
               raf.WriteByte(
    0, raf.CurrentPosition)
           
    Next
       
    Next
       raf.Close
       
    Return buffer
    End Sub
    Usage example:
    Code:
    Dim b() As Byte = BitmapToBMP(xui.LoadBitmap(File.DirAssets, "smiley.png"))
    File.WriteBytes("C:\Users\H\Downloads""test.bmp", b)
     
    Levit, MarcoRome, OliverA and 4 others 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