private int hasCameraPermission;
private List<String> permissions = new ArrayList<>();
private final static int PERMISSION_CODE = 100;
private Bitmap mBitmap=null;
private String mImagePath = null;
Step-1
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkCameraPermissions()) {
openCamera();
} else {
requestCameraPermissions();
}
} else {
openCamera();
}
private boolean checkCameraPermissions() {
hasCameraPermission= ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
if (hasCameraPermission== PackageManager.PERMISSION_GRANTED) {
return true;
}
return false;
}
@RequiresApi(api = Build.VERSION_CODES.M)
private void requestCameraPermissions() {
if (hasCameraPermission!= PackageManager.PERMISSION_GRANTED) {
permissions.add(android.Manifest.permission.CAMERA);
}
if (!permissions.isEmpty()) {
requestPermissions(permissions.toArray(new String[permissions.size()]), PERMISSION_CODE);
}
}
Step-2
private void openCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST);
}
Step-3
@Overridepublic void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == CAMERA_REQUEST) {
if (data != null && data.getExtras() != null) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP Uri mUri = getImageUri(getApplicationContext(), photo);
// CALL THIS METHOD TO GET THE ACTUAL PATH File mFile = new File(getRealPathFromURI(mUri));
// Save a file: path for use with ACTION_VIEW intents mImagePath = mFile.getAbsolutePath();
Bitmap bm = BitmapFactory.decodeFile(mImagePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos); //bm is the bitmap object byte[] byteArrayImage = baos.toByteArray();
String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
byte[] decodeResponse = Base64.decode(encodedImage, Base64.DEFAULT | Base64.NO_WRAP);
mBitmap= BitmapFactory.decodeByteArray(decodeResponse, 0, decodeResponse.length); // load
mBitmap= Bitmap.createScaledBitmap(mBitmap, 400, 400, false);
imageView.setImageBitmap(mBitmap);
}
}
}
public Uri getImageUri(Context mContext, Bitmap image) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(mContext.getContentResolver(), image, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(index);
}
No comments:
Post a Comment