Android Code Snippet [B4X] Convert bitmap to BMP format

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)

B4X:
Sub BitmapToBMP (img As B4XBitmap) As Byte()
   Dim Padding As Int = 4 - ((img.Width * 3) Mod 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")), 0, 2, 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:
B4X:
Dim b() As Byte = BitmapToBMP(xui.LoadBitmap(File.DirAssets, "smiley.png"))
File.WriteBytes("C:\Users\H\Downloads", "test.bmp", b)
 
Top