Android Question Array to bitmap

AlpVir

Well-Known Member
Licensed User
Longtime User
I have a big 2-dimensional array in which each element contains an int that corresponds to an RGB color.
How to turn this array into a bitmap file (BMP, JPG or PNG is the same thing)?
Thank you for your attention
 

derez

Expert
Licensed User
Longtime User
Something like this:
B4X:
Sub Globals
Dim pnl As Panel
Dim cnvs As Canvas
Dim a(100,100) As Int
End Sub

Sub Activity_Create(FirstTime As Boolean)
pnl.Initialize("")
cnvs.Initialize(pnl)
For x = 0 To 98
    For y = 0 To 99
        cnvs.DrawLine(x,y,x+1,y,a(x,y),1)
    Next
Next
Dim out As OutputStream
out = File.OpenOutput(File.DirRootExternal , "test.jpg",False)
cnvs.Bitmap.WriteToStream(out,100,"JPG")
End Sub
 
Upvote 0

James Chamblin

Active Member
Licensed User
Longtime User
You can use JavaObject to access the setPixels method of the bitmap like so:
B4X:
Sub Globals

   Dim bmp As Bitmap 'final bitmap
   Dim i As ImageView 'imageview to hold final bitmap
End Sub

Sub Activity_Create(FirstTime As Boolean)
   Dim a(10000) As Int 'array of colors in argb format

   'We will first fill the array with a black circle in a white square
   Dim x As Int
   Dim y As Int
   For x = 0 To 99
     For y = 0 To 99
       If (x-50)*(x-50)+(y-50)*(y-50) < 2500 Then
         a(x+y*100) = 0xff000000 'black
       Else
         a(x+y*100) = 0xffffffff 'white
       End If
     Next
   Next
  
   bmp.InitializeMutable(100,100) 'initialize the bitmap as mutable
   Dim jo As JavaObject = bmp 'create a java object and point it to the bitmap
   jo.RunMethod("setPixels",Array As Object(a,0,100,0,0,100,100)) 'run the setPixels method
   i.Initialize("") 'initialize the imageView
   i.SetBackgroundImage(bmp) 'set the imageView background to the bitmap
   Activity.AddView(i,10dip,10dip,100dip,100dip) 'add the imageView to the activity
End Sub

You can find information on the setPixels parameters here.
 
Upvote 0

AlpVir

Well-Known Member
Licensed User
Longtime User
The latter solution is faster and compact.
I then added a few lines to save the file.
B4X:
    Dim out As OutputStream
    Dim tempbitmap As Bitmap
    tempbitmap = i.Bitmap
    out = File.OpenOutput(File.DirRootExternal , NamePNG,False)
    tempbitmap.WriteToStream (out,100,"PNG")
    out.Close
Tanks
 
Upvote 0

sorex

Expert
Licensed User
Longtime User
or use the canvas.drawpoint method which is even more compact and is actually .setpixel but called different.
 
Upvote 0

mast4rbug

Member
Licensed User
Longtime User
Just to add a comment about the solution, (The first one) DrawPoint is WAYYYYY faster than Drawline. Just my 2 cents.
Cedric
 
Upvote 0
Top