Android Code Snippet [B4X] Bytes To File

This code is no longer needed. Use File.WriteBytes / ReadBytes.

Write an array of bytes to a file and read a file into an array of bytes.

B4X:
Sub BytesToFile (Dir As String, FileName As String, Data() As Byte)
   Dim out As OutputStream = File.OpenOutput(Dir, FileName, False)
   out.WriteBytes(Data, 0, Data.Length)
   out.Close
End Sub

Sub FileToBytes (Dir As String, FileName As String) As Byte()
   Return Bit.InputStreamToBytes(File.OpenInput(Dir, FileName))
End Sub

Note that you can convert complex objects (and simple objects) to bytes and vice versa with B4XSerializator from the RandomAccessFile library

Tags: Bytes, Serialization

Working with bytes? Check BytesBuilder: https://www.b4x.com/android/forum/t...implifies-working-with-arrays-of-bytes.89008/
 
Last edited:

sorex

Expert
Licensed User
Longtime User
why don't you use B4A to encrypt the photo and decrypt it before showing it in the app?
 

cambopad

Active Member
Licensed User
Longtime User
why don't you use B4A to encrypt the photo and decrypt it before showing it in the app?
Sorry I don't know how to do it with B4A! Is it fast if using it with picture? What lib can I use for that purpose?
 

DickD

Active Member
Licensed User
And what about strings?

B4X:
Dim s As String = "abcde"
Dim bytes() As Byte = s.GetBytes("UTF8")
'and back
s = BytesToString(bytes, 0, bytes.Length, "UTF8")

And bitmaps?

B4X:
Public Sub ImageToBytes(Image As Bitmap) As Byte()
   Dim out As OutputStream
   out.InitializeToBytesArray(0)
   Image.WriteToStream(out, 100, "JPEG")
   out.Close
   Return out.ToBytesArray
End Sub

Public Sub BytesToImage(bytes() As Byte) As Bitmap
   Dim In As InputStream
   In.InitializeFromBytesArray(bytes, 0, bytes.Length)
   Dim bmp As Bitmap
   bmp.Initialize2(In)
   Return bmp
End Sub

You second example of BytesToImage results in a run time error of "error loading bitmap" on the last line: bmp.Initialize(In)
I copied and pasted the code with bytes() being previously defined from an SQL query:
B4X:
Dim bytes() As Byte
Dim In As InputStream
cursor1 = SQL1.ExecQuery("SELECT * FROM PersonalInfo WHERE ID = 1")
cursor1.Position = 0
bytes = cursor1.GetBlob("image")
In.InitializeFromBytesArray(bytes, 0, bytes.Length)
   Dim bmp As Bitmap
   bmp.Initialize2(In)
 

DickD

Active Member
Licensed User
The code is correct. Please start a new thread in the questions forum and post the code that inserts the image to the database.
Ahhhhhh........ For reasons I can't explain this has started working. I had other duties today. When I came in at 6:00 I reran the program and it worked. I made no changes since yesterday. No one else working on this project but me. I have a programmer friend who likes to blame these things on "stray neutrinos".
 
Top