Android Question Convert blob to image for storage in File.DirAssets

Good day, I have a problem I do not know if someone who has experience can support me with it, I'm trying using jRDC to connect to a MySQL database and so far all good, I'm working with an ImageSlider, but so far only one sequence passes of existing images in the File.DirAssets.

however I have a table in the database that has fields of type blob, mediumblob, but I have not managed to visualize the images in blob, some idea of how to pass a Byte variable to image to be able to save them to File.DirAssets that is, I want to pass the blob images to images to the File.DirAssets. Any way to do it?

Thank you very much in advance
 

zed

Active Member
Licensed User
Dir Assets is read-only.
It is not possible to save files in this folder.
You must use xui.defaultfolder.

Get database image/blob and load to bitmap
B4X:
 Dim Buffer() As Byte  = res.GetBlob("Image") 'res = ResultSet
 Dim InputStream1 As InputStream
 InputStream1.InitializeFromBytesArray(Buffer, 0, Buffer.Length)
 Dim Bmp As Bitmap
 Bmp.Initialize2(InputStream1)
 InputStream1.Close
 imvImage.Bitmap = Bmp
Now that you have the bmp, all you have to do is save it.

Something like that
B4X:
Dim InStr As InputStream = InputStream1
Dim OutStr As OutputStream = File.OpenOutput(xui.defaultfolder,"image.jpg",False)
File.Copy2(InStr,OutStr)
OutStr.Close
 
Last edited:
Upvote 0
First of all thank you very much for the prompt response zed, I tried the code you suggested and I see that if you store it in the path, but my question is the following: How can I access that saved path with a cycle for to show in the sequence of images?

I explain what I have so far, based on my problem of needing an imageSlider to make a sequence of images in automatic, whose values must read them from the database through jDCR2 which is working but in the example that I found in the forum for the Slider is the following:
B4X:
Sub Globals
    'These global variables will be redeclared each time the activity is created.
    Private btnEmail As Button
    Private btnFacebook As Button
    Private btnGoogle As Button
    Private lblSignup As Label
    
    Private ImageSlider1 As ImageSlider
    Private MyList, MyList2, MyListBlob As List
    Private lblFlag As Label
    Private Idx As Int
    
    
    
    Private btnNext As Button
    Private btnPrev As Button
    Private btnPlay As Button
    Private LabelView As Label
    
    Private ver As Boolean = False
    Private edtPassword As EditText
    Private Label2 As Label
    Private ImageViewBlop As ImageView
'    Private ArregloBlop As DBResult
End Sub
MyList=File.ListFiles(File.DirAssets)
    For Each f As String In MyList
        If f.EndsWith(".png") Or f.EndsWith(".jpg") Then
            MyList2.Add(f)
        End If
    Next
    ImageSlider1.WindowBase.Color=Colors.White
    ImageSlider1.NumberOfImages = MyList2.Size
    If FirstTime Then
        timer1.Initialize("timer1", 2500)
    End If
    ImageSlider1.PrevImage
    btnNext_Click
    timer1.Enabled = Not(timer1.Enabled)
Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("splashui")
    MyList.Initialize
    MyList2.Initialize
    MyListBlob.Initialize

    
    Wait For (GetLogoComercio) Complete (Answer As Boolean)
    
    If Answer=True Then
        
    End If
    
    
'    GetImagesFromDir
    
    MyList=File.ListFiles(File.DirAssets)
    For Each f As String In MyList
        If f.EndsWith(".png") Or f.EndsWith(".jpg") Then
            MyList2.Add(f)
        End If
    Next
    ImageSlider1.WindowBase.Color=Colors.White
    ImageSlider1.NumberOfImages = MyList2.Size
    If FirstTime Then
        timer1.Initialize("timer1", 2500)
    End If
    ImageSlider1.PrevImage
    btnNext_Click
    timer1.Enabled = Not(timer1.Enabled)
    
    
End Sub

Sub ImageSlider1_GetImage (Index As Int) As ResumableSub
    Idx=Index
    
    Return xui.LoadBitmapResize(File.DirAssets,MyList2.Get(Index), _
    ImageSlider1.WindowBase.Width/2, ImageSlider1.WindowBase.Height, True)   
    
    
End Sub

Sub Timer1_Tick
    btnNext_Click
End Sub

Private Sub btnNext_Click
    ImageSlider1.NextImage
    
End Sub

'Method for recovering from database with blob SQL ...
Sub GetLogoComercio As ResumableSub
    
Dim respuesta As Boolean
    
    Dim req As DBRequestManager = CreateRequest
    Dim cmd As DBCommand = CreateCommand("Select_logo_comercios", Null)
    Wait For (req.ExecuteQuery(cmd, 0, Null)) JobDone(j As HttpJob)
    If j.Success Then
        req.HandleJobAsync(j, "req")
        Wait For (req) req_Result(res As DBResult)
'        'work with result
        req.PrintTable(res)
        Log(res.Columns)
'        ArregloBlop=res
        'ListViewListTable.Clear
        For Each row() As Object In res.Rows
            Dim oBitMap As Bitmap
            Dim buffer() As Byte
            buffer = row(res.Columns.Get("LOGO"))
            oBitMap = req.BytesToImage(buffer)
            'ListViewListTable.AddTwoLinesAndBitmap(row(1) & CRLF & row(4), "See more...", oBitMap)
            'ListViewListTable.AddTwoLinesAndBitmap(row(3), MyFormat(row(4)),oBitMap)
            Log("name:" & row(0))
            'preparamos para pasar a imagen
            Dim InputStream1 As InputStream
            InputStream1.InitializeFromBytesArray(buffer, 0, buffer.Length)
            Dim Bmp As Bitmap
            Bmp.Initialize2(InputStream1)
            InputStream1.Close
            ImageViewBlop.Bitmap=Bmp
            
            'guardamos la imagen
            Dim InStr As InputStream = InputStream1
            Dim OutStr As OutputStream = File.OpenOutput(xui.defaultfolder,row(1)&".jpg",False)
            File.Copy2(InStr,OutStr)
            OutStr.Close
            
            

        Next
        respuesta = True
    Else
        respuesta = False
        Log("ERROR: " & j.ErrorMessage)
    End If
    j.Release

    Return respuesta 
End Sub
 
Upvote 0
After much trying I achieved what I wanted but not with the ImageSlider library since there is no function that refers to adding a bitmap (AddBitmap) so what I did was to use an ImageView, two buttons (Next, Previous) and a Timer that makes the function of passing the sequence of images, as mentioned above the data is read from a table whose field is of blob type to pass the sequence of images.

As I mentioned before it may not be the right way but at least it meets what I require at this time, here I leave the code in case someone needs it:

B4X:
#Region  Project Attributes
    #ApplicationLabel: Image Slider Example
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: portrait
    #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#End Region

Sub Process_Globals
    ' Variables globales aquí
    Dim MyListBlob As List ' Lista para almacenar las imágenes BLOB
    Dim ImageIndex As Int
End Sub

Sub Globals
    ' Declaraciones de variables locales aquí
    Private imgSlider As ImageView
    Private btnPrevious As Button
    Private btnNext As Button
    Private Timer1 As Timer
End Sub

'obtener los datos con jRDC del ejemplo de Erel: https://www.b4x.com/android/forum/threads/b4x-jrdc2-b4j-implementation-of-rdc-remote-database-connector.61801/
Sub GetLogoComercio As ResumableSub
    
Dim respuesta As Boolean
    
    Dim req As DBRequestManager = CreateRequest
    Dim cmd As DBCommand = CreateCommand("Select_logo_comercios", Null)
    Wait For (req.ExecuteQuery(cmd, 0, Null)) JobDone(j As HttpJob)
    If j.Success Then
        req.HandleJobAsync(j, "req")
        Wait For (req) req_Result(res As DBResult)

        req.PrintTable(res)

        
        For Each row() As Object In res.Rows
            Dim oBitMap As Bitmap
            Dim buffer() As Byte
            buffer = row(res.Columns.Get("LOGO"))
            oBitMap = req.BytesToImage(buffer)
            
            
            Dim InputStream1 As InputStream
            InputStream1.InitializeFromBytesArray(buffer, 0, buffer.Length)
            Dim bmp As Bitmap
            bmp.Initialize2(InputStream1)
            'almacea los bmp a la lista que será recorrida
            MyListBlob.Add(bmp)
                        
            
        Next
        respuesta = True
    Else
        respuesta = False
        Log("ERROR: " & j.ErrorMessage)
    End If
    j.Release

    Return respuesta
End Sub

Sub Activity_Create(FirstTime As Boolean)
    If FirstTime Then
        ' Inicializa la lista de imágenes BLOB (cambia esto con tu código para cargar las imágenes)
        MyListBlob.Initialize
        
        ' Llama a la función para cargar las imágenes desde la base de datos
        Wait For (GetLogoComercio) Complete (Answer As Boolean)
    
    If Answer=True Then
        ' Configura el diseño de la interfaz de usuario
            Activity.LoadLayout("Main")
            
            ' Inicializa el índice de imagen actual
            ImageIndex = 0
            
            ' Inicializa el temporizador para cambiar de imagen cada 3 segundos
            Timer1.Initialize("Timer1", 3000) ' 3000 ms = 3 segundos
            Timer1.Enabled = True
        Else
            ' Si hay un error al cargar las imágenes desde la base de datos, maneja el error
            Log("Error al cargar las imágenes desde la base de datos")
        End If
    End If
End Sub

Sub Timer1_Tick
    ' Cambia a la siguiente imagen en la lista
    ImageIndex = (ImageIndex + 1) Mod MyListBlob.Size
    UpdateImage
End Sub

Sub UpdateImage
    If MyListBlob.Size > 0 Then
        imgSlider.Bitmap = MyListBlob.Get(ImageIndex)
    End If
End Sub

Sub btnPrevious_Click
    ' Cambia a la imagen anterior
    ImageIndex = (ImageIndex - 1 + MyListBlob.Size) Mod MyListBlob.Size
    UpdateImage
End Sub

Sub btnNext_Click
    ' Cambia a la siguiente imagen
    ImageIndex = (ImageIndex + 1) Mod MyListBlob.Size
    UpdateImage
End Sub

I leave a demonstration of the operation, ignore the bark of Sirus my dog in the video, is that walking solving this detail I asked your croquettes XD
 
Upvote 0
Top