Android Question Is it possible that Cameraview is saved file to database

achank

New Member
Hi, I would like to thank you in advance and my high appreciation for the existence of this B4X software. This software is very helpful in developing projects
Sorry beforehand I used Google Translate to ask because my English is not good.
Straight to the point, I can already use this library
https://www.b4x.com/android/forum/t...-pictures-record-video-with-the-camera.83196/
https://www.b4x.com/android/forum/threads/externalstorage-access-sd-cards-and-usb-sticks.90238/
to record videos and take pictures and save them to internal or external storage. I use a webcam connected to an Android TVbox.
I am currently developing a project so that I can send and save videos directly to a database server
Is there a library or code example I can use? Thank you for your attention.
B4X:
Region  Project Attributes
    #ApplicationLabel: CCTVcam
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: landscape
    #CanInstallToExternalStorage: False
#End Region

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

#AdditionalJar: androidx.legacy:legacy-support-core-utils

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Private Timer1 As Timer
    Private Timer2 As Timer
    Private Timer3 As Timer
    Private player1 As SimpleExoPlayer
    
    Private Storage As ExternalStorage
    Private FoldersStack As List
    Private UpItem As ExternalFile
    
    Private cc As ContentChooser
    Private OldIntent As Intent
End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.

    Private cam As CameraView
    Private btnStart As Button
    Private btnStop As Button
    Private btnSnapshot As Button
    Private PanelSlide As Panel
    Private ButtonSet As Button
    Private ButtonPick As Button
    Private LabelFolder As Label
    Private CheckBox1 As CheckBox
    Dim myBool As Boolean
    Private LabelCountdown As Label
    Dim Hitung As Int
    Private ButtonPlay As Button
    Private StartTime As Long
    Private LabelTimeUp As Label
    Private ButtonOpenFolder As Button
    Private SimpleExoPlayerView1 As SimpleExoPlayerView
    Private ImageView1 As ImageView
    
    Private rpRuntimePermissions As RuntimePermissions
    Dim sf As StringFunctions2
    Dim Directori As String
    
    Dim id As String
    Dim NamaFile As String
    Dim MimeType As String
    Dim Direc As String
    Dim OF As Boolean
    Dim digital As Typeface
End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    If FirstTime Then
        Storage.Initialize (Me, "Storage")
        FoldersStack.Initialize
        UpItem.Initialize
        sf.Initialize       
    End If
    Activity.LoadLayout("Layout1")
    
    player1.Initialize("player")
    ButtonPlay.Visible = False
    LabelTimeUp.Visible = False
    PanelSlide.Visible = False
    SimpleExoPlayerView1.Visible = False
    ImageView1.Visible = False
    LabelCountdown.Visible = False
    btnStop.Enabled = False
    btnStart.Enabled = False
    btnSnapshot.Enabled = False
    
    cam.Facing = "FRONT"
    cam.VideoQuality = "HIGHEST"
    cam.setSessionVideo
    setRotation(cam, 180)   
    Cnf_canvas
    
    Timer1.Initialize("Timer1", 1500)
    Timer2.Initialize("Timer2", 1500)
    Timer3.Initialize("Timer3", 500)   
    
    digital = Typeface.LoadFromAssets("Digital Display.ttf")
    LabelTimeUp.Typeface = digital   
End Sub

Private Sub ConvertMillisecondsToString(t As Long) As String
    Dim hours, minutes, seconds As Int
    hours = t / DateTime.TicksPerHour
    minutes = (t Mod DateTime.TicksPerHour) / DateTime.TicksPerMinute
    seconds = (t Mod DateTime.TicksPerMinute) / DateTime.TicksPerSecond
    Return $"$2.0{hours}:$2.0{minutes}:$2.0{seconds}"$
End Sub

Sub Cnf_canvas
    Dim cs2 As CSBuilder
    cs2.Initialize
    cs2.Image(LoadBitmap(File.DirAssets, "Logo Setting.png"), 40dip, 40dip, False)
    cs2.PopAll
    ButtonSet.Text = cs2
End Sub

Sub AnimationPanel
    If myBool  Then
        PanelSlide.SetLayoutAnimated(0, 40%x, -10%y, 60%x, 10%y)
        PanelSlide.SetLayoutAnimated(1000, 40%x, 3%y, 60%x, 10%y)
    Else
        PanelSlide.SetLayoutAnimated(0, 40%x, 3%y, 60%x, 10%y)
        PanelSlide.SetLayoutAnimated(1000, 40%x, -10%y, 60%x, 10%y)
    End If
End Sub

Sub Timer1_Tick
    LabelCountdown.Visible = True
    Hitung = Hitung-1
    LabelCountdown.Text = Hitung
    LabelCountdown.SetTextColorAnimated(0, Colors.Red)
    LabelCountdown.SetTextColorAnimated(2000, Colors.Transparent)
    If Hitung <= 0 Then
        Hitung = 0
        LabelCountdown.Visible = False
        cam.setSessionVideo
        DateTime.DateFormat = "ddMMyyyy HHmmss"
        Log("Time: " & DateTime.Date(DateTime.Now))
        cam.startCapturingVideo(Directori,"Vid " & DateTime.Date(DateTime.Now) & " .mp4")
        Timer2.Enabled = True
        If Timer3.Enabled = False Then
            StartTime = DateTime.Now
            Timer3.Enabled = True
        Else
            Timer3.Enabled = False
        End If
        Timer1.Enabled = False       
    End If
End Sub

Sub Timer2_Tick
    ButtonPlay.Visible = True   
    ButtonPlay.SetTextColorAnimated(0, Colors.Red)
    ButtonPlay.SetTextColorAnimated(2000, Colors.Transparent)
End Sub

Sub Timer3_Tick
    LabelTimeUp.Visible = True
    Dim milliseconds As Long = DateTime.Now - StartTime
    LabelTimeUp.Text = ConvertMillisecondsToString(milliseconds)
End Sub

Sub setRotation(v As View, Angle As Float)
    Dim jo = v As JavaObject
    jo.RunMethod("setRotation", Array As Object(Angle))
End Sub
Sub Cam_onCameraClosed()
    Log($"Cam_onCameraClosed()"$)
End Sub
Sub Cam_onCameraOpened(options As Object)
    Log($"Cam_onCameraOpened()"$)
End Sub
Sub Cam_onExposureCorrectionChanged(newValue As Float, bounds() As Float, fingers() As Object)
    Log($"Cam_onExposureCorrectionChanged(${newValue},${bounds},${fingers})"$)
End Sub
Sub Cam_onFocusEnd(success As Boolean, x As Int, y As Int)
    Log($"Cam_onFocusEnd(${success},${x},${y})"$)
End Sub
Sub Cam_onOrientationChanged(orientation As Int)
    Log($"Cam_onOrientationChanged(${orientation})"$)
End Sub
Sub Cam_onPictureTaken(jpeg() As Byte)
    Log($"Cam_onPictureTaken()"$)
    DateTime.DateFormat = "ddMMyyyy HHmmss"
    Dim FileName = "Image " & DateTime.Date(DateTime.Now) & " .jpg" As String
    File.WriteBytes(File.DirInternal, FileName , jpeg)
    FiletoExtStorage(FileName)   
    File.Delete(File.DirInternal, FileName)
    cam.start
End Sub
Sub Cam_onVideoTaken(path As String, filename As String)
    Log($"Cam_onVideoTaken(${path},${filename})"$)
    Timer2.Enabled = False
    Timer3.Enabled = False
    ButtonPlay.Visible = False
    LabelTimeUp.Visible = False
    cam.start
End Sub
Sub Cam_onZoomChanged(newValue As Float, bounds() As Float, fingers() As Object)
    Log($"Cam_onZoomchanged(${newValue},${bounds},${fingers})"$)
End Sub

Sub Activity_Resume
    cam.start
    If IsRelevantIntent(Activity.GetStartingIntent) Then
        Dim in As JavaObject = Activity.GetStartingIntent
        Dim uri As String = in.RunMethod("getParcelableExtra", Array("android.intent.extra.STREAM"))
        Try
            ShowInfo(uri)
        Catch
            Log(LastException)
        End Try
    End If
End Sub
Sub Activity_Pause (UserClosed As Boolean)
    cam.pause
End Sub

Sub btnStart_Click
    Hitung = 6
    Timer1.Enabled = True
    btnStart.Enabled = False
    btnSnapshot.Enabled = False   
    ButtonOpenFolder.Enabled = False
    btnStop.Enabled = True
End Sub

Sub btnStop_Click
    If cam.Started Then
        cam.stop
    End If
    btnSnapshot.Enabled = True
    ButtonOpenFolder.Enabled = True
    btnStart.Enabled = True
    btnStop.Enabled = False
End Sub

Sub btnSnapshot_Click
    cam.setSessionPicture
    cam.captureSnapshot
End Sub

Private Sub ButtonSet_Click
    PanelSlide.Visible = True
    myBool = myBool <> True
    AnimationPanel
End Sub

Private Sub ButtonPick_Click
    Storage.SelectDir(CheckBox1.Checked)
    Wait For Storage_ExternalFolderAvailable
    FoldersStack.Clear
    EnterFolder(Storage.Root)
    FindFolder
    btnStart.Enabled = True
    btnSnapshot.Enabled = True
End Sub

Private Sub EnterFolder (folder As ExternalFile)
    FoldersStack.Add(folder)
    Dim sb As StringBuilder
    sb.Initialize
    For Each f As ExternalFile In FoldersStack
        If f = Storage.Root Then
            sb.Append("Root")           
        Else
            sb.Append(" / ").Append(f.Name)
        End If
    Next
End Sub

Sub FindFolder As Boolean
    'Define Storage: Phone storage (=true) or SD card (false).
    Dim AllExternal() As String = rpRuntimePermissions.GetAllSafeDirsExternal("")
    Dim PersistantUri As String
    Dim ExternalDir As String        'External storage.
    Dim sText As String            'The "Identifier" of the folder.
    Dim iPos As Int
    
    'Read the contents of the PersistantUri file - the URI of the previous (current) folder.
    PersistantUri = File.ReadString(File.DirInternal, "PersistantUri")

    sText = PersistantUri
    sText = sf.Left(sText, sf.InString(sText, "%"))
    iPos = sf.InString(sText, "/")
    Do While iPos>=0
        sText = sf.Right(sText, sText.Length-iPos-1)
        iPos = sf.InString(sText, "/")
    Loop
    If PersistantUri.StartsWith("content://com.android.externalstorage.documents/tree/") Then
        Dim i As Int = PersistantUri.LastIndexOf("/")
        Directori = PersistantUri.SubString(i + 1)
        Directori = Directori.Replace("%3A", "/")
        Directori = Directori.Replace("%2F", "/")
        Log("Directori1: " & Directori )
        Dim strSplit() As String
        strSplit=Regex.Split("/",Directori)
        For i = 0 To strSplit.Length-1
            If strSplit(0) = "primary" Then
                Directori = Directori.Replace("primary", "/storage/emulated/0")
                LabelFolder.Text = Directori
            Else
                If i = strSplit.Length-1 Then
                    Directori = Directori.Replace(Directori, "/storage/" & Directori)
                    LabelFolder.Text = Directori
                End If               
            End If
        Next
        Log("Directori2: " & Directori )
    End If
    
    If AllExternal.Length >1 Then
        'There is an external SD card.
        ExternalDir = AllExternal(1)
        If sf.InString(ExternalDir, sText) >= 0 Then
            'The current folder is on the SD card.
            Log("ExternalDir1: " & ExternalDir)
            Return False
        Else
            'The current folder is in Phone Memory.
            Log("ExternalDir2: " & ExternalDir)
            Return True
        End If
    Else
        'No SD card.
        Return True
    End If
End Sub

Sub FiletoExtStorage(FileToCopy As String)
    Dim inpstr As InputStream          = File.OpenInput(File.DirInternal,FileToCopy)         'Create an Inputstream from the Sourcefile to copy
    Dim destfile As ExternalFile     = Storage.CreateNewFile(Storage.Root,FileToCopy)           'create the file
    Dim os As OutputStream             = Storage.OpenOutputStream(destfile)                    'Create an Outputstream to the destfile
    File.Copy2(inpstr,os)                                                                  'Copy file
    inpstr.Close                                                                        'Close inputstr
    os.Close                                                                              'Close Outputstream
End Sub

Private Sub ButtonOpenFolder_Click
    OF = OF <> True
    If OF  Then
        ImageView1.Visible = True
        SimpleExoPlayerView1.Visible = True
        OpenFolder
    Else
        player1.Pause
        ImageView1.Visible = False
        SimpleExoPlayerView1.Visible = False
    End If
    
End Sub
Sub OpenFolder
    cc.Initialize("CC")
    cc.Show("*/*", "Choose File")
    Wait For CC_Result (Success As Boolean, Dir As String, FileName As String)
    If Success Then
        ShowInfo(FileName)
'        Log("NamaFile: " & NamaFile)
'        Log("MimeType: " & MimeType)
'        Log("Direc: " & Direc)
        Direc = Direc.Replace("%20" , " ")
        Direc = Direc.Replace("/" & NamaFile , "")
        Log("Direc: " & Direc)
        If MimeType = "image/jpeg" Then
            SimpleExoPlayerView1.Visible = False
            ImageView1.Visible = True
            ImageView1.Bitmap = LoadBitmap(Direc,NamaFile)
        else If MimeType = "video/mp4" Then
            ImageView1.Visible = False
            SimpleExoPlayerView1.Visible = True       
            player1.Initialize("player1")   
            player1.Prepare(player1.CreateFileSource(Direc,NamaFile))
            SimpleExoPlayerView1.Player = player1
            player1.Volume = 0
            player1.Play
        End If   
    End If
End Sub
Sub ShowInfo(uri As String)   
    Try
        NamaFile = GetFileInfoByIndex("_display_name", uri)
    Catch
        NamaFile = "error"
    End Try
    Try
        MimeType = GetFileInfoByIndex("mime_type", uri)
    Catch
        MimeType = "error"
    End Try
End Sub

Sub GetFileInfoByIndex(column As String, uri As String) As String
    
    Dim results As String
    Dim Cur As Cursor
    Dim Uri1 As Uri
    Dim cr As ContentResolver
    cr.Initialize("")

    'if viewing by gallery
    'If uri.StartsWith("content://media/") Then
    If uri.StartsWith("content://com.android.externalstorage.documents/document/") Then
        Dim i As Int = uri.LastIndexOf("/")
        id = uri.SubString(i + 1)
        id = id.Replace("%3A", "/")
        id = id.Replace("%2F", "/")
        Dim strSplit() As String
        strSplit=Regex.Split("/",id)
        For i = 0 To strSplit.Length-1
            If strSplit(0) = "primary" Then
                Direc = id.Replace("primary", "/storage/emulated/0")
            Else
                If i = strSplit.Length-1 Then
                    Direc = id.Replace(id, "/storage/" & id)
                End If
            End If
        Next
        Uri1.Parse(uri)
        Cur = cr.Query(Uri1, Null, "document", Array As String(id), Null)
        Cur.Position = 0
        If Cur.RowCount <> 0 Then
            For i = 0 To Cur.ColumnCount - 1
                If Cur.GetColumnName(i) <> Null Then
                    If Cur.GetColumnName(i) = column Then
                        results = Cur.GetString2(i)
                        Exit
                    End If
                End If
            Next
        End If
    Else
        Log("parsing uri2")
        'content://com.android.externalstorage.documents/document/primary%3AUpdateSBXtv%2F3109148.jpg
        Uri1.Parse(uri)
        Cur = cr.Query(Uri1, Null, Null, Null, Null)
        Cur.Position = 0
        If Cur.RowCount <> 0 Then
            For i = 0 To Cur.ColumnCount - 1
                If Cur.GetColumnName(i) <> Null Then
                    If Cur.GetColumnName(i) = column Then
                        results = Cur.GetString2(i)
                        Exit
                    End If
                End If
            Next
        End If
    End If
    
    Cur.Close
    
    Return results
    
End Sub

Private Sub IsRelevantIntent(in As Intent) As Boolean
    If in.IsInitialized And in <> OldIntent And in.Action = in.ACTION_SEND Then
        OldIntent = in
        Return True
    End If
    Return False
End Sub
 

Attachments

  • cameraview2.jpg
    cameraview2.jpg
    108.2 KB · Views: 88
  • cameraview1.jpg
    cameraview1.jpg
    194.6 KB · Views: 88
Last edited:
Top