Public Sub ImageToBytes2(Image As B4XBitmap, Quality As Int) As Byte()
Dim out As OutputStream
out.InitializeToBytesArray(0)
Image.WriteToStream(out, Quality, "JPEG")
out.Close
Return out.ToBytesArray
End Sub
Public Sub BytesToImage(bytes() As Byte) As B4XBitmap
Dim In As InputStream
In.InitializeFromBytesArray(bytes, 0, bytes.Length)
#if B4A or B4i
Dim bmp As Bitmap
bmp.Initialize2(In)
#else
Dim bmp As Image
bmp.Initialize2(In)
#end if
Return bmp
End Sub
Sub LoadImageFromBlob(xSQL1 As SQL, xTable As String, xField As String, xID As Long) As B4XBitmap
If xID <= 0 Or xTable.Trim = "" Or xField.Trim = "" Then Return Null
Dim Bmp As B4XBitmap = Null
Dim blobSize As Long = SQL.ExecQuerySingleResult2("SELECT IFNULL(LENGTH(" & xField & "), 0) FROM " & xTable & " WHERE id = ?", Array As String(xID))
If blobSize > 0 Then
Dim rs As ResultSet = xSQL1.ExecQuery2("SELECT " & xField & " FROM " & xTable & " WHERE id = ? LIMIT 1", Array As String(xID))
If rs.NextRow Then
Dim Buffer() As Byte = rs.GetBlob(xField)
Bmp = BytesToImage(Buffer)
End If
rs.Close
End If
Return Bmp
End Sub
Sub SaveImageAsBLOB(bmp As Image, xSQL1 As SQL, xTable As String, xField As String, xID As Int) As Boolean
Dim b() As Byte = ImageToBytes2(bmp, 80)
Dim i As Int = xSQL1.ExecQuerySingleResult("SELECT count(*) FROM " & xTable & " WHERE id = '" & xID & "'")
If i = 0 Then
Dim s As String = "INSERT INTO " & xTable & " (" & xField & ") VALUES (?)"
xSQL1.ExecNonQuery2(s, Array (b))
Else
Dim s As String = "UPDATE " & xTable & " SET " & xField & " = ? WHERE id = ?"
xSQL1.ExecNonQuery2(s, Array (b, xID))
End If
Return True
End Sub