Android Question How to convert image to byte?

Pravee7094

Active Member
Hi all,
When I used JRDC2, to convert image to byte is very simple. The example code is

B4X:
        Dim BufferU () As Byte
        If ImageView.IsInitialized Then
            BufferU = CreateRequest.ImageToBytes(ImageView.Bitmap)
        End If

But I used PHP method, What is the exact code to convert image to byte?
I think I don't know what word used instead of CreateRequest.

Any body Help? Any suggestion?

Thanks
Praveen
 

josejad

Expert
Licensed User
Longtime User
Not sure, maybe this?

 
Upvote 0

emexes

Expert
Licensed User
or maybe this?

1615889639032.png
 
Upvote 0

aeric

Expert
Licensed User
Longtime User
B4X:
Sub Button1_Click
    PutImage(File.DirApp, "test.png")
End Sub

Client:
Sub PutImage(Dir As String, Filename As String)
    Dim cmd As DBCommand = CreateCommand("insert_file", Array As Object(Filename, File.ReadBytes(Dir, Filename)))
    Dim j As HttpJob = CreateRequest.ExecuteBatch(Array(cmd), Null)
    Wait For(j) JobDone(j As HttpJob)
    If j.Success Then
        Log("Inserted successfully!")
    End If
    j.Release
End Sub

Table schema:
CREATE TABLE "imagefile" (
    "id"    INTEGER,
    "filename"    TEXT,
    "filebyte"    BLOB,
    PRIMARY KEY("id" AUTOINCREMENT)
)

config.properties:
sql.insert_file=INSERT INTO imagefile (filename, filebyte) VALUES (?, ?)
 
Upvote 0

TILogistic

Expert
Licensed User
Longtime User
see class DBRequestManager

B4X:
'Reads a file and returns the file as a bytes array.
Public Sub FileToBytes(Dir As String, FileName As String) As Byte()
    Dim out As OutputStream
    out.InitializeToBytesArray(0)
    Dim In As InputStream = File.OpenInput(Dir, FileName)
    File.Copy2(In, out)
    out.Close
    Return out.ToBytesArray
End Sub
#if Not(B4J)
'Converts an image to a bytes array (for BLOB fields).
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
'Converts a bytes array to an image (for BLOB fields).
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
#End If
 
Upvote 0

Peter Simpson

Expert
Licensed User
Longtime User
You can use the following to learn the basics,
The attached codes loads an image file, converts it into bytes and then resaves that file again, but you can easily modify it to save to a database or to anywhere that you like.
 

Attachments

  • Project.zip
    176.1 KB · Views: 341
Upvote 0
Top