Android Question Native camera intents help

Douglas Farias

Expert
Licensed User
Longtime User
Hi all.
later many time the google made a new documentation, clear and more easy about how use the camera.
on this link u will see intent codes and one example.

https://developer.android.com/training/camera/photobasics.html


i m trying compile this intents for b4a

i m with a problem on the get thumbnail
i m using StartActivityForResult to call the camera intent take picture and later get the result (path) where is the file.

the first simple result its a thumbnail, like show on google example i made this.

Google Example
B4X:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        Bundle extras = data.getExtras();
        Bitmap imageBitmap = (Bitmap) extras.get("data");
        mImageView.setImageBitmap(imageBitmap);
    }
}

What i made
B4X:
Sub ion_Event (MethodName As String, Args() As Object) As Object
  If Args(0) = -1 Then ' = RESULT_OK
      Dim i As Intent = Args(1)
    Log(Args(1))
    Log(i.HasExtra("data"))
    Log(i.GetExtra("data"))
    Private filename As String = i.GetData.SubString(i.GetData.LastIndexOf("/") + 1)
    Private dir As String = i.GetData.SubString2(0,i.GetData.Length - filename.Length)
    Log(filename)
    Log(dir)
    Private bm As Bitmap '= i.GetExtra("data")
    Dim input As InputStream = File.OpenInput(dir, filename)
    bm.Initialize2(input)
    input.Close
      
    ImageView1.Bitmap = bm
   End If
 
Return Null
End Sub

the logs is
Installing file.
** Activity (main) Pause, UserClosed = false **
PackageAdded: package:b4a.example
** Service (starter) Create **
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = false **
sending message to waiting queue (OnActivityResult)
running waiting messages (1)
Intent { act=inline-data dat=content://media/external/images/media/513 flg=0x1 (has extras) }
true
null
513
content://media/external/images/media/
Error occurred on line: 48 (Main)
java.io.FileNotFoundException: content:/media/external/images/media/513: open failed: ENOENT (No such file or directory)
at libcore.io.IoBridge.open(IoBridge.java:456)
at java.io.FileInputStream.<init>(FileInputStream.java:76)
at anywheresoftware.b4a.objects.streams.File.OpenInput(File.java:209)
at b4a.example.main._ion_event(main.java:511)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at anywheresoftware.b4a.shell.Shell.runMethod(Shell.java:703)
at anywheresoftware.b4a.shell.Shell.raiseEventImpl(Shell.java:337)
at anywheresoftware.b4a.shell.Shell.raiseEvent(Shell.java:247)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at anywheresoftware.b4a.ShellBA.raiseEvent2(ShellBA.java:134)
at anywheresoftware.b4a.BA.raiseEvent(BA.java:153)
at anywheresoftware.b4j.object.JavaObject$1.invoke(JavaObject.java:237)
at java.lang.reflect.Proxy.invoke(Proxy.java:397)
at $Proxy0.ResultArrived(Unknown Source)
at anywheresoftware.b4a.BA$4.run(BA.java:513)
at anywheresoftware.b4a.BA.setActivityPaused(BA.java:398)
at b4a.example.main$ResumeMessage.run(main.java:296)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6946)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
at libcore.io.Posix.open(Native Method)
at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
at libcore.io.IoBridge.open(IoBridge.java:442)
... 26 more
** Activity (main) Resume **
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = false **

where is the problem here?
Like on the description
The Android Camera application encodes the photo in the return Intent delivered to onActivityResult() as a small Bitmap in the extras, under the key"data". The following code retrieves this image and displays it in an ImageView.

i m trying convert this i.GetExtra("data") to bitmap but dont works.
i m tryied open a InputStream and i have the same problem.

what is the error here?
like show on the logs the image (thumbnail) its saved with path
content://media/external/images/media/513

but if i try load this put into a bitmap i got the same error.

ps: i m already tryed add .jpg and the error continue.
ps2: if i use Log(i.ExtrasToString) this show
Bundle[{data=android.graphics.Bitmap@f2a52b1, bitmap-data=true}]
the bitmaps is here, now i need know how take this :rolleyes:



thx
 
Last edited:

Douglas Farias

Expert
Licensed User
Longtime User
Ok, i made this works
B4X:
Sub ion_Event (MethodName As String, Args() As Object) As Object
  If Args(0) = -1 Then '= RESULT_OK
      Dim i As Intent = Args(1)
    Dim jo As JavaObject = i
    Private bm As Bitmap = jo.RunMethod("getParcelableExtra", Array As Object("data"))  
    ImageView1.Bitmap = bm
   End If
Return Null
End Sub

i m not good with intents etc..
but i will try folow the another intents , to get full size photo, etc...
if someone know pls help me or post here

thx
 
Last edited:
Upvote 0

Douglas Farias

Expert
Licensed User
Longtime User
i dont know why, but with

B4X:
Private bm AsBitmap = jo.RunMethod("getParcelableExtra", ArrayAs Object("data"))

i get the image with correct orientation

and always wrong with this code

B4X:
DiminAsInputStream = File.OpenInput("ContentDir", i.GetData)
 
Upvote 0

Douglas Farias

Expert
Licensed User
Longtime User
Ok later some try i made this.

GOOGLE EXAMPLE
B4X:
String mCurrentPhotoPath;

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
        imageFileName,  /* prefix */
        ".jpg",         /* suffix */
        storageDir      /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = "file:" + image.getAbsolutePath();
    return image;
}


WHAT I MADE
B4X:
'GET FILE NAME, LIKE ANDROID API DOCUMENTATION
Sub GetFileName As String
    DateTime.TimeFormat = "yyyyMMdd_HHmmss"
    Private timestamps As String = DateTime.Time(DateTime.Now)
    Private imageFileName As String = "JPEG_" & timestamps & "_.jpg"
    Return imageFileName
End Sub


the google code, create a temp file where will be saved the picture, i dont know make this in b4a, i made the code only to return the filename.



OK, later i need invoke the camera like google show on the code. (here i need some help)

GOOGLE EXAMPLE
B4X:
static final int REQUEST_TAKE_PHOTO = 1;

private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
            ...
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(this,
                                                  "com.example.android.fileprovider",
                                                  photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
        }
    }
}


WHAT I MADE
B4X:
Sub Button1_Click
    Dim DIRECTORY_PICTURES As String = NativeMe.RunMethod("DIRECTORY_PICTURES", Null) 'GET PICTURE DIRECTORY LIKE SHOW ON GOOGLE API DOCUMENTATION
   
    Dim getExternalFilesDir As String = NativeMe.RunMethod("getExternalFilesDir", Array(Null)) 'GET EXTERNAL FILES DIRECTORY LIKE SHOW ON GOOGLE API DOCUMENTATION

    File.MakeDir(getExternalFilesDir,DIRECTORY_PICTURES) 'MAKE A THIS PICTURES IF NOT EXIST
   
    fp = File.Combine(getExternalFilesDir,DIRECTORY_PICTURES) 'COMBINE THE DIR WITH DEFAULT PICTURE FOLDER NAME
   
    'RESULTS 
    Log("Folder: "& fp)
    Log("FileName: "& GetFileName)
    imagefile = GetFileName

    Dim i As Intent
    i.Initialize("android.media.action.IMAGE_CAPTURE", "")
    i.PutExtra("output", ParseUri("file://" & File.Combine(fp,GetFileName))) 'OPEN THE INTENT WITH THE CORRECT FOLDER AND CORRECT FILE NAME
      StartActivityForResult(i)
   
End Sub


I get the getExternalFilesDir and the DIRECTORY_PICTURES like google code, later i combine with filename.
before start the StartActivityForResult(i) i put a output with the folder and filename.

All ok.



The problem now its this sub.

B4X:
'GET FULL SIZE IMAGE
Sub ion_Event (MethodName As String, Args() As Object) As Object
  If Args(0) = -1 Then '= RESULT_OK
      Dim i As Intent = Args(1)
    Log(i.ExtrasToString)

    If File.Exists(fp,imagefile) Then
        Log("Image Saved") 'HERE IS THE IMAGE
        ImageView1.Bitmap = LoadBitmapSample(fp,imagefile,ImageView1.Width,ImageView1.Height) 'IMAGE IS LOADED ON IMAGEVIEW
    End If

   End If
Return Null
End Sub

The image its saved ok, but the log of i.ExtrasToString is = not initialized

Question 1 = How can i get the image result path, where this is stored?
on the google code this use "startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);" but here on b4a i dont know call this args.

Question 2 = how can i get the full size image with correct orientation?
with the thumb i found the fix here
https://www.b4x.com/android/forum/threads/native-camera-intents-help.69183/#post-438964
but i dont know with the full size picture


Question 3 = On google example this use a temp file, and with the intent the temp file is transformed into a image file, how can i make like google example here on b4a? how create a image temp file and use this on intent?

Question 4 = Can i get the bitmap on intent? get the bitmap on ion_Event like thumbnail example? (not only the path and filename)

Question 5 = On google example this use "com.example.android.fileprovider", what is this and how can i use here in b4a on this intent?

Question 6 = Like the question 1, how can i know if the picture is saved with sucess?
in some devices the output extra its ignored and the camera save the image with default name and dir like this
/mnt/sdcard/DCIM/Camera/2012-11-02 13.58.38.jpg
how can i check if the camera intent as ignored my output extra? and if this is ignore how can i get the default folder and file name saved?

this is a common problem in forum (ez camera have this problem of default name) and intent examples have same error.
the pictures are saved, the unique problem its know where and how get this.


would appreciate if someone with superior knowledge help, this will help not only me, have a lot of questions about native camera on the forum with no solution. :(

Attached I am sending two examples
Avtivity 1 = Open native camera and get the thumbnail with correct orientation and put it into a imageview
Avtivity 2 = Open native camera and get the full size picture with problem of orientation and no args on result


thx again.
 

Attachments

  • teste camera.zip
    102.6 KB · Views: 397
Upvote 0
Top