ImagePicker
ImagePicker copied to clipboard
FRONT_CAMERA doesnt work as expected?
Here's the code which uses the latest ImagePicker (2.3.22):
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.github.drjacky.imagepicker.ImagePicker;
import com.github.drjacky.imagepicker.constant.ImageProvider;
public class MainActivity extends AppCompatActivity {
Button btnTakePicture;
ImageView imgProfPic;
int CAMERA_PERMISSION_REQUEST_CODE = 1324;
ActivityResultLauncher<Intent> launcher=
registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),(ActivityResult result)->{
if(result.getResultCode()==RESULT_OK){
Uri uri=result.getData().getData();
// Use the uri to load the image
}else if(result.getResultCode()==ImagePicker.RESULT_ERROR){
// Use ImagePicker.Companion.getError(result.getData()) to show an error
}
});
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnTakePicture = (Button) findViewById(R.id.btnTakePicture);
imgProfPic = (ImageView) findViewById(R.id.profPic);
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA)
== PackageManager.PERMISSION_DENIED){
ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.CAMERA},
CAMERA_PERMISSION_REQUEST_CODE);
}
btnTakePicture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
launcher.launch(
ImagePicker.with(MainActivity.this)
.maxResultSize(512,512,true)
.provider(ImageProvider.FRONT_CAMERA)
.createIntent()
);
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == CAMERA_PERMISSION_REQUEST_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Camera permission granted.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Camera permission denied.", Toast.LENGTH_LONG).show();
}
}
}
}
Running it on Pixel 3 (Android 12), the back camera will be opened. My impression while reading the example is .provider(ImageProvider.FRONT_CAMERA) will automatically open the front camera, and thus the camera switch button is disabled/hidden.