Don't understand why I am not getting my Image? - android

I am working on an demo application where I am taking picture then save it.
I want to display picture inside Image view . I don't understand why it is not working . I recently tried out some solution but non of them worked for me .
Is there anyone who can tell me what's wrong with my code .
// This is my code
private Button takePictureButton;
private ImageView imageView;
private Uri file;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
takePictureButton = (Button) findViewById(R.id.button_image);
imageView = (ImageView) findViewById(R.id.imageview);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
takePictureButton.setEnabled(false);
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE }, 0);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 0) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED&&grantResults[2]==PackageManager.PERMISSION_GRANTED) {
takePictureButton.setEnabled(true);
}
}
}
public void takePicture(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
file = Uri.fromFile(getOutputMediaFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, file);
startActivityForResult(intent, 100);
}
private static File getOutputMediaFile(){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "CameraDemo");
if (!mediaStorageDir.exists()){
if (!mediaStorageDir.mkdirs()){
Log.d("CameraDemo", "failed to create directory");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
return new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100) {
//Code that bind image with ImageView
if (resultCode == RESULT_OK) {
imageView.setMaxHeight(100);
imageView.setMaxWidth(100);
imageView.setImageURI(null);
imageView.setImageURI(file);
}
}
//Thanks in advance

I dont really understand what are you doing at here. But :
if (resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
imageView.setMaxHeight(100);
imageView.setMaxWidth(100);
imageView.setImageURI(uri);
}
Replace this code on your activityResult, it is working for me.

Try this way it will work
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ivImage.setImageBitmap(thumbnail);
}
For more See this http://www.theappguruz.com/blog/android-take-photo-camera-gallery-code-sample

In My case it worked for me:
private static Bitmap Image = null;
private static Bitmap rotateImage = null;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.e("resultCode", Integer.toString(resultCode));
Log.e("requestCode", Integer.toString(requestCode));
Log.e("Inside If","Success");
Uri mImageUri = data.getData();
try {
Image = MediaStore.Images.Media.getBitmap(this.getContentResolver(), mImageUri);
if (getOrientation(getApplicationContext(), mImageUri) != 0) {
Matrix matrix = new Matrix();
matrix.postRotate(getOrientation(getApplicationContext(), mImageUri));
if (rotateImage != null)
rotateImage.recycle();
rotateImage = Bitmap.createBitmap(Image, 0, 0, Image.getWidth(), Image.getHeight(), matrix,true);
imageView.setImageBitmap(rotateImage);
//saveImagetoFolder(rotateImage);
} else {
imageView.setImageBitmap(Image);
// saveImagetoFolder(Image);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Related

Androind ImageView in Fragment

I am trying to put an image on my fragment, but the image is not showing up. I am certain that it was working just yesterday but now it is not. Any help is appreciated.
This code is in my Fragment:
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
mUser = (User) getArguments().getSerializable(ARGS_USER);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_picture_picker, container, false);
mImageView = v.findViewById(R.id.imageView);
mSelectImageButton = v.findViewById(R.id.select_image);
mSelectImageButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, IMG_REQUEST);
}
});
return v;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == IMG_REQUEST && resultCode == Activity.RESULT_OK && data != null){
Uri path = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), path);
mImageView.setImageBitmap(bitmap);
mImageView.setVisibility(View.VISIBLE);
mUser.setProfilePicture(bitmap);
}catch(IOException e){
e.printStackTrace();
}
}
}
Actually you are not using the Volley. Please change the heading of your question. You are accessing the Gallery and showing the image inside the imageView. Use the below code for accessing the image from camera as well as gallery.
if (action.equals("CAMERA")) {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
// Check Permissions Now
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, ACTION_REQUEST_CAMERA);
} else {
openCamera();
}
} else if (action.equals("GALLERY")) {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Check Permissions Now
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, ACTION_REQUEST_GALLERY);
} else {
openGallery();
}
}
private void openCamera(){
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
getActivity().startActivityForResult(cameraIntent, ACTION_REQUEST_CAMERA);
}
private void openGallery(){
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
Intent chooser = Intent.createChooser(galleryIntent, "Choose a Picture");
getActivity().startActivityForResult(chooser, ACTION_REQUEST_GALLERY);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
System.out.println("OnActivityResult");
System.out.println("resultCode: "+resultCode+"\n"+"requestCode: "+requestCode);
ImageOperations operations = new ImageOperations();
if (resultCode == RESULT_OK) {
if (requestCode == ACTION_REQUEST_GALLERY) {
System.out.println("select file from gallery ");
Uri selectedImageUri = data.getData();
renderProfileImage(selectedImageUri,operations);
} else if (requestCode == ACTION_REQUEST_CAMERA) {
System.out.println("select file from camera ");
Bitmap photo = (Bitmap) data.getExtras().get("data");
String name = "profile_pic.png";
operations.saveImageToInternalStorage(photo,getActivity(),name);
profile_image.setImageBitmap(photo);
}
}
}
private void renderProfileImage(Uri selectedImageUri,ImageOperations operations) {
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), selectedImageUri);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, bytes);
String name = "profile_pic.png";
operations.saveImageToInternalStorage(bitmap,getActivity(),name);
profile_image.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
private class ImageOperations {
public boolean saveImageToInternalStorage(Bitmap image, Context context, String name) {
try {
// Use the compress method on the Bitmap object to write image to
// the OutputStream
FileOutputStream fos = context.openFileOutput("profile_pic.png", Context.MODE_PRIVATE);
// Writing the bitmap to the output stream
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
return true;
} catch (Exception e) {
Log.e("saveToInternalStorage()", e.getMessage());
return false;
}
}
public Bitmap getThumbnail(Context context,String filename) {
String fullPath = Environment.getDataDirectory().getAbsolutePath();
Bitmap thumbnail = null;
// Look for the file on the external storage
try {
if (isSdReadable() == true) {
thumbnail = BitmapFactory.decodeFile(fullPath + "/" + filename);
}
} catch (Exception e) {
Log.e("Image",e.getMessage());
}
// If no file on external storage, look in internal storage
if (thumbnail == null) {
try {
File filePath = context.getFileStreamPath(filename);
FileInputStream fi = new FileInputStream(filePath);
thumbnail = BitmapFactory.decodeStream(fi);
} catch (Exception ex) {
Log.e("getThumbnail()", ex.getMessage());
}
}
return thumbnail;
}
public boolean isSdReadable() {
boolean mExternalStorageAvailable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
mExternalStorageAvailable = true;
Log.i("isSdReadable", "External storage card is readable.");
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
Log.i("isSdReadable", "External storage card is readable.");
mExternalStorageAvailable = true;
} else {
// Something else is wrong. It may be one of many other
// states, but all we need to know is we can neither read nor write
mExternalStorageAvailable = false;
}
return mExternalStorageAvailable;
}
}
action is like what you want to do. ACTION_REQUEST_GALLERY and ACTION_REQUEST_CAMERA use some integer constants like 100 and 101. profileImage is your ImageView.

Capture from camera Image is not clear(Blurry) in Android

I Have a Problem with the Camera Capture Image.its set blurry.
I searched lots of but i can't Get Solutions
I don't know How to solve issue
Here is My Code Which i Used For Camera Capture Image
private void cameraIntent()
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
///method to get Images
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
} else {
if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
Toast.makeText(context, "Your Permission is needed to get access the camera", Toast.LENGTH_LONG).show();
}
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1);
}
} else {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
byte[] imageInByte = bytes.toByteArray();
long lengthbmp = imageInByte.length;
File destination = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
iv_upld.setImageBitmap(thumbnail);
}

Android: setImageBitmap from sdCard not work

I want select photo by user from sd card and show in ImageView
My code :
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
}
catch (IOException e) {
e.printStackTrace();
}
imgOne.setImageBitmap(bm);
But this code not work
This code for onActivityResult after select photo by user
My class :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
Log.i("error", "" + requestCode);
final ImageView imgOne = (ImageView) G.currentActivity.findViewById(R.id.imgOne);
if (requestCode == 1) {
Bitmap bm = null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
//ByteArrayOutputStream bytes = new ByteArrayOutputStream();
//bm.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
//bm = Bitmap.createScaledBitmap(bm, 600, 600, true);
}
catch (IOException e) {
e.printStackTrace();
}
imgOne.setImageBitmap(bm);
Log.i("error", "" + bm);
}
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
final Uri imageUri = data.getData();
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
imageView.setImageBitmap(selectedImage);
} catch (IOException e) {
e.printStackTrace();
}
}
}

Images are not show in ListView Item on Camera click in Android [duplicate]

I need to push an intent to default camera application to make it take a photo, save it and return an URI. Is there any way to do this?
private static final int TAKE_PICTURE = 1;
private Uri imageUri;
public void takePhoto(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photo = new File(Environment.getExternalStorageDirectory(), "Pic.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(intent, TAKE_PICTURE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PICTURE:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ImageView imageView = (ImageView) findViewById(R.id.ImageView);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
imageView.setImageBitmap(bitmap);
Toast.makeText(this, selectedImage.toString(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
.show();
Log.e("Camera", e.toString());
}
}
}
}
Try the following I found here
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0);
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && requestCode == 0) {
String result = data.toURI();
// ...
}
}
It took me some hours to get this working. The code it's almost a copy-paste from developer.android.com, with a minor difference.
Request this permission on the AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
On your Activity, start by defining this:
static final int REQUEST_IMAGE_CAPTURE = 1;
private Bitmap mImageBitmap;
private String mCurrentPhotoPath;
private ImageView mImageView;
Then fire this Intent in an onClick:
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.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
Log.i(TAG, "IOException");
}
// Continue only if the File was successfully created
if (photoFile != null) {
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
}
}
Add the following support method:
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 = Environment.getExternalStoragePublicDirectory(
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;
}
Then receive the result:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
mImageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath));
mImageView.setImageBitmap(mImageBitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
What made it work is the MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath)), which is different from the code from developer.android.com. The original code gave me a FileNotFoundException.
I found a pretty simple way to do this. Use a button to open it using an on click listener to start the function openc(), like this:
String fileloc;
private void openc()
{
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = null;
try
{
f = File.createTempFile("temppic",".jpg",getApplicationContext().getCacheDir());
if (takePictureIntent.resolveActivity(getPackageManager()) != null)
{
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,FileProvider.getUriForFile(profile.this, BuildConfig.APPLICATION_ID+".provider",f));
fileloc = Uri.fromFile(f)+"";
Log.d("texts", "openc: "+fileloc);
startActivityForResult(takePictureIntent, 3);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 3 && resultCode == RESULT_OK) {
Log.d("texts", "onActivityResult: "+fileloc);
// fileloc is the uri of the file so do whatever with it
}
}
You can do whatever you want with the uri location string. For instance, I send it to an image cropper to crop the image.
Try the following I found Here's a link
If your app targets M and above and declares as using the CAMERA permission which is not granted, then attempting to use this action will result in a SecurityException.
EasyImage.openCamera(Activity activity, int type);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
EasyImage.handleActivityResult(requestCode, resultCode, data, this, new DefaultCallback() {
#Override
public void onImagePickerError(Exception e, EasyImage.ImageSource source, int type) {
//Some error handling
}
#Override
public void onImagesPicked(List<File> imagesFiles, EasyImage.ImageSource source, int type) {
//Handle the images
onPhotosReturned(imagesFiles);
}
});
}
Call the camera through intent, capture images, and save it locally in the gallery.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
someActivityResultLauncher.launch(cameraIntent);}
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
bitmap = (Bitmap) Objects.requireNonNull(result.getData()).getExtras().get("data");
}
imageView.setImageBitmap(bitmap);
saveimage(bitmap);
}
private void saveimage(Bitmap bitmap){
Uri images;
ContentResolver contentResolver = getContentResolver();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
images = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
}else {
images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, System.currentTimeMillis() +".jpg");
contentValues.put(MediaStore.Images.Media.MIME_TYPE, "images/*");
Uri uri = contentResolver.insert(images, contentValues);
try {
OutputStream outputStream = contentResolver.openOutputStream(Objects.requireNonNull(uri));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
Objects.requireNonNull(outputStream);
//
}catch (Exception e){
//
e.printStackTrace();
}
}
try this code
Intent photo= new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(photo, CAMERA_PIC_REQUEST);

Android camera intent

I need to push an intent to default camera application to make it take a photo, save it and return an URI. Is there any way to do this?
private static final int TAKE_PICTURE = 1;
private Uri imageUri;
public void takePhoto(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photo = new File(Environment.getExternalStorageDirectory(), "Pic.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(intent, TAKE_PICTURE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PICTURE:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ImageView imageView = (ImageView) findViewById(R.id.ImageView);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
imageView.setImageBitmap(bitmap);
Toast.makeText(this, selectedImage.toString(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
.show();
Log.e("Camera", e.toString());
}
}
}
}
Try the following I found here
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0);
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && requestCode == 0) {
String result = data.toURI();
// ...
}
}
It took me some hours to get this working. The code it's almost a copy-paste from developer.android.com, with a minor difference.
Request this permission on the AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
On your Activity, start by defining this:
static final int REQUEST_IMAGE_CAPTURE = 1;
private Bitmap mImageBitmap;
private String mCurrentPhotoPath;
private ImageView mImageView;
Then fire this Intent in an onClick:
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.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
Log.i(TAG, "IOException");
}
// Continue only if the File was successfully created
if (photoFile != null) {
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
}
}
Add the following support method:
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 = Environment.getExternalStoragePublicDirectory(
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;
}
Then receive the result:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
mImageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath));
mImageView.setImageBitmap(mImageBitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
What made it work is the MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath)), which is different from the code from developer.android.com. The original code gave me a FileNotFoundException.
I found a pretty simple way to do this. Use a button to open it using an on click listener to start the function openc(), like this:
String fileloc;
private void openc()
{
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = null;
try
{
f = File.createTempFile("temppic",".jpg",getApplicationContext().getCacheDir());
if (takePictureIntent.resolveActivity(getPackageManager()) != null)
{
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,FileProvider.getUriForFile(profile.this, BuildConfig.APPLICATION_ID+".provider",f));
fileloc = Uri.fromFile(f)+"";
Log.d("texts", "openc: "+fileloc);
startActivityForResult(takePictureIntent, 3);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 3 && resultCode == RESULT_OK) {
Log.d("texts", "onActivityResult: "+fileloc);
// fileloc is the uri of the file so do whatever with it
}
}
You can do whatever you want with the uri location string. For instance, I send it to an image cropper to crop the image.
Try the following I found Here's a link
If your app targets M and above and declares as using the CAMERA permission which is not granted, then attempting to use this action will result in a SecurityException.
EasyImage.openCamera(Activity activity, int type);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
EasyImage.handleActivityResult(requestCode, resultCode, data, this, new DefaultCallback() {
#Override
public void onImagePickerError(Exception e, EasyImage.ImageSource source, int type) {
//Some error handling
}
#Override
public void onImagesPicked(List<File> imagesFiles, EasyImage.ImageSource source, int type) {
//Handle the images
onPhotosReturned(imagesFiles);
}
});
}
Call the camera through intent, capture images, and save it locally in the gallery.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
someActivityResultLauncher.launch(cameraIntent);}
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
bitmap = (Bitmap) Objects.requireNonNull(result.getData()).getExtras().get("data");
}
imageView.setImageBitmap(bitmap);
saveimage(bitmap);
}
private void saveimage(Bitmap bitmap){
Uri images;
ContentResolver contentResolver = getContentResolver();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
images = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
}else {
images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, System.currentTimeMillis() +".jpg");
contentValues.put(MediaStore.Images.Media.MIME_TYPE, "images/*");
Uri uri = contentResolver.insert(images, contentValues);
try {
OutputStream outputStream = contentResolver.openOutputStream(Objects.requireNonNull(uri));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
Objects.requireNonNull(outputStream);
//
}catch (Exception e){
//
e.printStackTrace();
}
}
try this code
Intent photo= new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(photo, CAMERA_PIC_REQUEST);

Categories

Resources