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
 
Not sure, maybe this?

 
Upvote 0
or maybe this?

1615889639032.png
 
Upvote 0
B4X:
Sub Button1_Click
    PutImage(File.DirApp, "test.png")
End Sub

Code:
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

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

Code:
sql.insert_file=INSERT INTO imagefile (filename, filebyte) VALUES (?, ?)
 
Upvote 0
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
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

Upvote 0
Back
Top