Spanish ¿Cómo guardar foto en SMARTPHONE, CAMEX2?; Resuelto

JAVIERGARCIA

Member
Licensed User
Longtime User
También añadí en el Manifest.

upload_2019-2-9_14-57-46.png
 

Attachments

  • upload_2019-2-9_14-57-27.png
    upload_2019-2-9_14-57-27.png
    40 KB · Views: 226

josejad

Expert
Licensed User
Longtime User
Hola Javier, por favor, pon el código como texto con las etiquetas Code, que hace más sencillo verlo.
Me pillas fuera, pero ese código lo pongo en la sub TakePicture de la clase Camera2.

Saludos,
 
Last edited:

JAVIERGARCIA

Member
Licensed User
Longtime User
Hola Javier, por favor, pon el código cómo texto con las etiquetas Code, que hace más sencillo verlo.
Me pillas fuera, pero ese código lo pongo en la sub TakePicture de la clase Camera2.

Saludos,


Solo modifico el Takepicture en el MAIN
En El CamEx2, el procedimiento se llama TakepictureNow, es diferente,, (me equivoqué antes con el nombre)
Las librerías actualizadas a la versión 1.10. Todo bien según indicaciones. Pero nada.


Este a texto, todo el código que hay.
Saludos

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

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

Sub Process_Globals
Private frontCamera As Boolean = False
Private VideoMode As Boolean = False
Private VideoFileDir, VideoFileName As String
Private MyTaskIndex As Int
Private rp As RuntimePermissions
End Sub

Sub Globals
Private cam As CamEx2
Private pnlCamera As Panel
Private pnlPicture As Panel
Private pnlBackground As Panel
Private btnEffects As Button
Private btnScene As Button
Private buttons As List
Private btnAutoExposure As Button
Private btnFocus As Button
Private ProgressBar1 As ProgressBar
Private openstate, busystate As Boolean
Private btnRecord As Button
Private btnMode As Button
Private btnCamera As Button
Private barZoom As SeekBar
End Sub

Sub Activity_Create(FirstTime As Boolean)
VideoFileDir = rp.GetSafeDirDefaultExternal("")
VideoFileName = "1.mp4"
Activity.LoadLayout("1")
Activity.LoadLayout("StillPicture")
cam.Initialize(pnlCamera)
Log(cam.SupportedHardwareLevel)
buttons = Array(btnScene, btnAutoExposure, btnEffects, btnFocus, btnMode)
SetState(False, False, VideoMode)
End Sub

Sub Activity_Resume
OpenCamera(frontCamera)
End Sub


Sub OpenCamera (front As Boolean)
rp.CheckAndRequest(rp.PERMISSION_CAMERA)
Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
If Result = False Then
ToastMessageShow("No permission!", True)
Return
End If

SetState(False, False, VideoMode)
Wait For (cam.OpenCamera(front)) Complete (TaskIndex As Int)
If TaskIndex > 0 Then
MyTaskIndex = TaskIndex 'hold this index. It will be required in later calls.
Wait For(PrepareSurface) Complete (Success As Boolean)
End If
Log("Start success: " & Success)
SetState(Success, False, VideoMode)
If Success = False Then
ToastMessageShow("Failed to open camera", True)
End If
Log(cam.ActiveArraySize)
End Sub

Sub PrepareSurface As ResumableSub
SetState(False, busystate, VideoMode)
'sizes can be modified here
If VideoMode Then
cam.PreviewSize.Initialize(640, 480)
'Using a temporary file to store the video.
Wait For (cam.PrepareSurfaceForVideo(MyTaskIndex, VideoFileDir, "temp-" & VideoFileName)) Complete (Success As Boolean)
Else
cam.PreviewSize.Initialize(1920, 1080)
Wait For (cam.PrepareSurface(MyTaskIndex)) Complete (Success As Boolean)
End If
If Success Then cam.StartPreview(MyTaskIndex, VideoMode)
SetState(Success, busystate, VideoMode)
Return Success
End Sub

Sub btnCamera_Click
frontCamera = Not(frontCamera)
OpenCamera(frontCamera)
End Sub

Sub Activity_Pause (UserClosed As Boolean)
cam.Stop
End Sub

Sub btnMode_Click
VideoMode = Not(VideoMode)
If VideoMode Then
rp.CheckAndRequest(rp.PERMISSION_RECORD_AUDIO)
Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
If Result = False Then
ToastMessageShow("No permission!", True)
VideoMode = False
End If
End If
SetState(openstate, busystate, VideoMode)
PrepareSurface
End Sub

Sub btnRecord_Click
If VideoMode Then
CaptureVideo
Else
TakePicture
End If
End Sub

Sub CaptureVideo
Try
SetState(openstate, True, VideoMode)
If cam.RecordingVideo = False Then
cam.StartVideoRecording (MyTaskIndex)
Else
cam.StopVideoRecording (MyTaskIndex)
File.Copy(VideoFileDir, "temp-" & VideoFileName, VideoFileDir, VideoFileName)
ToastMessageShow($"Video file saved: $1.2{File.Size(VideoFileDir, VideoFileName) / 1024 / 1024} MB"$, True)
Wait For (PrepareSurface) Complete (Success As Boolean)
SetState(openstate, False, VideoMode)

End If
Catch
HandleError(LastException)
End Try
End Sub

Sub HandleError (Error As Exception)
Log("Error: " & Error)
ToastMessageShow(Error, True)
OpenCamera(frontCamera)
End Sub

Sub TakePicture
' Try
' SetState(openstate, True, VideoMode)
' Wait For(cam.FocusAndTakePicture(MyTaskIndex)) Complete (Data() As Byte)
' SetState(openstate, False, VideoMode)
' Dim bmp As Bitmap = cam.DataToBitmap(Data)
' Log("Picture taken: " & bmp)
' pnlBackground.SetVisibleAnimated(100, True)
' pnlPicture.SetBackgroundImage(bmp.Resize(pnlPicture.Width, pnlPicture.Height, True)).Gravity = Gravity.CENTER
' Sleep(4000)
' pnlBackground.SetVisibleAnimated(500, False)
' Catch
' HandleError(LastException)
' End Try
'Dim NombreFoto As String
Try
SetState(openstate, True, VideoMode)
Wait For(cam.FocusAndTakePicture(MyTaskIndex)) Complete (Data() As Byte)
SetState(openstate, False, VideoMode)
'Dim bmp As Bitmap = cam.DataToBitmap(Data)
'Log("Picture taken: " & bmp)

'NombreFoto ="NombreQueQuieras.jpg"
cam.DataToFile(Data, rp.GetSafeDirDefaultExternal(""), "foto.jpg")

Catch
HandleError(LastException)
End Try
End Sub

Sub pnlPicture_Click
pnlBackground.Visible = False
End Sub

Sub btnEffects_Click
Dim effects As List = cam.SupportedEffectModes
Dim i As Int = effects.IndexOf(cam.EffectMode)
i = (i + 1) Mod effects.Size
cam.EffectMode = effects.Get(i)
btnEffects.Text = effects.Get(i)
cam.StartPreview(MyTaskIndex, VideoMode)
End Sub

Sub btnScene_Click
Dim scenes As List = cam.SupportedSceneModes
Dim i As Int = scenes.IndexOf(cam.SceneMode)
i = (i + 1) Mod scenes.Size
cam.SceneMode = scenes.Get(i)
btnScene.Text = scenes.Get(i)
cam.StartPreview(MyTaskIndex, VideoMode)
End Sub

Sub btnAutoExposure_Click
Dim flashes As List = cam.SupportedAutoExposureModes
Dim i As Int = flashes.IndexOf(cam.AutoExposureMode)
i = (i + 1) Mod flashes.Size
cam.AutoExposureMode = flashes.Get(i)
btnAutoExposure.Text = flashes.Get(i)
cam.StartPreview(MyTaskIndex, VideoMode)
End Sub

Sub btnFocus_Click
Dim focuses As List = cam.SupportedFocusModes
Dim i As Int = focuses.IndexOf(cam.FocusMode)
i = (i + 1) Mod focuses.Size
cam.FocusMode = focuses.Get(i)
btnFocus.Text = focuses.Get(i)
cam.StartPreview(MyTaskIndex, VideoMode)
End Sub

'This sub enables or disables the various UI elements based on the current state.
Sub SetState(Open As Boolean, Busy As Boolean, Video As Boolean)
For Each b As Button In buttons
b.Visible = Open And Not(Busy)
Next
btnCamera.Visible = Not(Busy)
btnRecord.Visible = Open And (Video Or Not(Busy))
openstate = Open
ProgressBar1.Visible = Busy
busystate = Busy
VideoMode = Video
barZoom.Visible = Open
Dim btnRecordText As String
If VideoMode Then
If Busy Then
btnRecordText = Chr(0xF04D)
Else
btnRecordText = Chr(0xF03D)
End If
Else
btnRecordText = Chr(0xF030)
End If
btnRecord.Text = btnRecordText
End Sub

Sub barZoom_ValueChanged (Value As Int, UserChanged As Boolean)
Dim OriginalSize As Rect = cam.ActiveArraySize
Dim Zoom As Float = 1 + Value / 100 * (cam.MaxDigitalZoom - 1)
Dim Crop As Rect
Dim NewWidth As Int = OriginalSize.Width / Zoom
Dim NewHeight As Int = OriginalSize.Height / Zoom
Crop.Initialize(OriginalSize.CenterX - NewWidth / 2, OriginalSize.CenterY - NewHeight / 2, _
OriginalSize.CenterX + NewWidth / 2, OriginalSize.CenterY + NewHeight / 2)
cam.PreviewCropRegion = Crop
cam.StartPreview(MyTaskIndex, VideoMode)
End Sub
 

josejad

Expert
Licensed User
Longtime User
Disculpa, me confundí antes por hablar de memoria, el código para guardar la foto va en la Sub Takepicture de tu actividad.
Pues lo acabo de probar sin hacer ningún cambio y ha funcionado, la foto se guarda en el directorio de la aplicación con el nombre "foto.jpg"
(recuerda poner las etiquetas [ CODE]pega aquí tu código[ /CODE] (sin espacios en los corchetes) cuando pongas código
B4X:
cam.DataToFile(Data, rp.GetSafeDirDefaultExternal(""), "foto.jpg")

Screenshot_20190209-210946.png
 

JAVIERGARCIA

Member
Licensed User
Longtime User
uyyyy, con el mismo código del zip que te acabo de enviar, no?.. (si no era más que eso, como me decías)
Ya encabezo bien este hilo (no entiendo nada),, José, imagino que no tendrá que ver nada,,, pero yo voy a resetar los móviles, a ver que pasa.
 

josejad

Expert
Licensed User
Longtime User
Sí, con el zip sin modificarlo. Has mirado en esa carpeta? Tienes acceso a ella? (tienes la ruta sobre mi imagen) /.../Android/data/b4a.example3/files ?
 

JAVIERGARCIA

Member
Licensed User
Longtime User
si si, claro,,,en el mismo sitio indicado.. buscando desde administrador de archivos,,
no se Jose.. Otra cosa ha de ser a parte, y que no tiene nada que ver pues con el código. Estoy reseteando el primero ahora
 

f0raster0

Well-Known Member
Licensed User
Longtime User
Je,,, así encabezo el asunto del mensaje.: No entiendo nada
a question:

Cómo es posible que una misma app se comporte diferente en un móvil u otro.? No lo entiendo.

..existen millones de versiones hardware y software (diferentes versiones instaladas.. android 5+ sus actualizaciones)
Una de nuestras tablet no permite ver un pdf pero el mismo codigo si en otra.

Tips:
1) "No entiendo nada" cambiarlo por:
"no veo la foto guardada en Smartphone" o "¿Cómo guardar foto en Samrtphone?"

2) Crea un proyecto basado en los ejemplos, donde solamente guarde una foto.
(Usa una foto de baja resolución, puede ser que tu Smartphone está full de memoria)

3) Conecta tu Smartphone a tu PC o Laptop y ve a la ruta que te dice José.
.. buscando desde administrador de archivos
Ve manualmente a esa ruta..
 
Last edited:

JAVIERGARCIA

Member
Licensed User
Longtime User
Sí, con el zip sin modificarlo. Has mirado en esa carpeta? Tienes acceso a ella? (tienes la ruta sobre mi imagen) /.../Android/data/b4a.example3/files ?


Bueno, problema solventado
(me quedo con una duda, pero bueno, la doy por externa)
En un móvil me funciona bien (Samsung), en otro imposible (Huawei). Reseteados los dos.
Motivo: Ni idea.
Bueno, samsung´s he probado en tres diferentes. Ahí va bien todo y según indicaciones.
No se el motivo. No debiera no funcionar, ya lo se. Pero así es. Y de ahí, además, mi despiste.
Las indicaciones de José, perfectas. Ahí también fallaba yo.

, seguimos.
Gracias a todos.
 

JAVIERGARCIA

Member
Licensed User
Longtime User
..existen millones de versiones hardware y software (diferentes versiones instaladas.. android 5+ sus actualizaciones)
Una de nuestras tablet no permite ver un pdf pero el mismo codigo si en otra.

Tips:
1) "No entiendo nada" cambiarlo por:
"no veo la foto guardada en Smartphone" o "¿Cómo guardar foto en Samrtphone?"

2) Crea un proyecto basado en los ejemplos, donde solamente guarde una foto.
(Usa una foto de baja resolución, puede ser que tu Smartphone está full de memoria)

3) Conecta tu Smartphone a tu PC o Laptop y ve a la ruta que te dice José.

Ve manualmente a esa ruta..



Gracias f0raster0,,,,, ya me quedó resuelto todo. Ha sido una árdua pelea con los medios y con mi desconocimiento también, claro.

Doy esta batalla por resuelta.

Muchas Gracias
 
Top