How to fix NullPointerException: file when capturing picture from Camera - android

I am trying to capture an image using the camera, however on saving the file I get the following error:
java.lang.NullPointerException: file
at android.net.Uri.fromFile(Uri.java:452)
at com.example.denny.lostandfound.ReportFoundItem.dispatchTakePictureIntent(ReportFoundItem.java:84)
at com.example.denny.lostandfound.ReportFoundItem.access$000(ReportFoundItem.java:39)
at com.example.denny.lostandfound.ReportFoundItem$1.onClick(ReportFoundItem.java:169)
at android.view.View.performClick(View.java:5265)
at android.view.View$PerformClick.run(View.java:21534)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5728)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
I want to capture image directly from the camera and save it to a database. How can this be fixed?
AndroidManifest.xml file:
<uses-permission android:name="android.permission.INTERNET" />
<uses-feature android:name="android.hardware.camera"
android:required="true" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/icon"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.denny.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/filepaths" />
</provider>
<activity android:name=".Home">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>....
My ReportFoundItem.xml:
public class ReportFoundItem extends AppCompatActivity {
private DatabaseReference databaseFound;
private static final int CAPTURE_IMAGE = 1;
private Uri picUri;
private StorageReference mStorage;
private ProgressDialog mProgress;
private EditText etemail;
private EditText etphone;
private Spinner etcategory;
private Spinner etsub_category;
private Button btncapture;
private ImageView imageView;
private EditText etdate_found;
private EditText etlocation_found;
private EditText etdetails;
private void dispatchTakePictureIntent() {
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File file = getOutputMediaFile(1);
picUri = Uri.fromFile(file);
i.putExtra(MediaStore.EXTRA_OUTPUT,picUri); // set the image file
startActivityForResult(i, CAPTURE_IMAGE);
}
public File getOutputMediaFile(int type) {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "TRARC");
/**Create the storage directory if it does not exist*/
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
/**Create a media file name*/
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == 1){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".png");
} else {
return null;
}
return mediaFile;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_report_found_item);
mStorage = FirebaseStorage.getInstance().getReference();
databaseFound = FirebaseDatabase.getInstance().getReference("found");
etemail = (EditText)findViewById(R.id.etemail);
etphone = (EditText)findViewById(R.id.etphone);
etcategory = (Spinner)findViewById(R.id.etcategory);
etsub_category = (Spinner)findViewById(R.id.etsub_category);
btncapture = (Button)findViewById(R.id.btncapture);
imageView = (ImageView)findViewById(R.id.imageView);
etdate_found = (EditText) findViewById(R.id.etdate_found);
etlocation_found = (EditText) findViewById(R.id.etlocation_found);
etdetails = (EditText) findViewById(R.id.etdetails);
mProgress = new ProgressDialog(this);
btncapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dispatchTakePictureIntent();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAPTURE_IMAGE && resultCode == RESULT_OK){
mProgress.setMessage("Uploading Image...Please wait...");
mProgress.show();
final StorageReference filepath = mStorage.child("Found_Photos").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mProgress.dismiss();
//creating the upload object to store uploaded image details
Upload upload = new Upload(uri.toString(),taskSnapshot.getDownloadUrl().toString());
//adding an upload to firebase database
String uploadId = databaseFound.push().getKey();
databaseFound.child(uploadId).setValue(upload);
Uri downloadUri = taskSnapshot.getDownloadUrl();
Picasso.with(ReportFoundItem.this).load(downloadUri).fit().centerCrop().into(imageView);
//Toast.makeText(ReportFoundItem.this, "Uploading finished...", Toast.LENGTH_LONG).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
mProgress.setMessage("Uploaded " + ((int) progress) + "%...");
}
});//add on failure listener
}
}
private void reportFoundItem() {
String email = etemail.getText().toString().trim();
String phone = etphone.getText().toString().trim();
String category = etcategory.getSelectedItem().toString().trim();
String sub_category = etsub_category.getSelectedItem().toString().trim();
String date_found = etdate_found.getText().toString().trim();
String location_found = etlocation_found.getText().toString().trim();
String details = etdetails.getText().toString().trim();
//check if empty
if (!TextUtils.isEmpty(email)){
//getting the key
String id = databaseFound.push().getKey();
//save the data under lost
Found found = new Found(id, email, phone, category, sub_category, date_found, location_found, details);
//set the value under the id
databaseFound.child(id).setValue(found);
Toast.makeText(this, "Found Item added successfully!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Please enter all Fields!", Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.savetodb, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.save:
reportFoundItem();
ClearEditTextAfterDoneTask();
}
return true;
}
#Override
public void onBackPressed()
{
super.onBackPressed();
startActivity(new Intent(ReportFoundItem.this, Home.class));
finish();
}
public void ClearEditTextAfterDoneTask() {
etemail.getText().clear();
etphone.getText().clear();
etdate_found.getText().clear();
etlocation_found.getText().clear();
etdetails.getText().clear();
}
}
I expect to save the picture directly once I capture it from the camera.

Try this one ...
Image Captured....
private int REQUEST_IMAGE_CAPTURE = 100;
on Click ....
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
on ActivityResult ....
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
// Bundle extras = data.getExtras();
Bitmap bitmap = ImageUtils.getBitmapFromIntent(this, data);
mImage.setImageBitmap(bitmap);// mImage is a ImageView which is bind previously.
String imgPath = ImageUtils.createFile(this, bitmap);
File imageFile = new File(imgPath);
}
and other Method....
public class ImageUtils {
public static Bitmap getBitmapFromIntent(Context context,Intent data) {
Bitmap bitmap = null;
if (data.getData() == null) {
bitmap = (Bitmap) data.getExtras().get("data");
} else {
try {
bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
return bitmap;
}
public static String createFile(Context context, Bitmap data) {
Uri selectedImage = getImageUri(context,data);
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = context.getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
c.getColumnIndex(filePath[0]);
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
return picturePath;
}
public static Uri getImageUri(Context context, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(context.getContentResolver(), inImage, "Pet_Image", null);
return Uri.parse(path);
}
}
Note:- you are getting URI null because the image you capturing doesn't have any path. So URI return null..

#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();
}
user_image.setImageBitmap(thumbnail);
}
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm = null;
if (data != null) {
try {
bm =
MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(),
data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
user_image.setImageBitmap(bm);
}
check data is !=null to avoid nullpointer exception

this is how I did it in my project .
public void openCamera() {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File file = createImageFile();
boolean isDirectoryCreated = file.getParentFile().mkdirs();
Log.d("===PickFragment", "openCamera: isDirectoryCreated: " + isDirectoryCreated);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri tempFileUri = FileProvider.getUriForFile(getActivity().getApplicationContext(),
"com.scanlibrary.provider", // As defined in Manifest
file);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempFileUri);
} else {
Uri tempFileUri = Uri.fromFile(file);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempFileUri);
}
startActivityForResult(cameraIntent, ScanConstants.START_CAMERA_REQUEST_CODE);
}
private File createImageFile() {
clearTempImages();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new
Date());
File file = new File(Environment
.getExternalStorageDirectory().getPath(), "IMG_" + timeStamp +
".jpg");
fileUri = Uri.fromFile(file);
return file;
}

Related

Android app crop an image and send it to another activity

I'm creating an android app where the user crops the image, the cropped image is shown and then has to be sent in the Result activity.
The problem I have is that when I send the image, it sends me the original uncropped image.
So I wonder, am I wrong something or the image is not really cropped?
Can anyone help me figure out how to display the cropped image in the Result activity?
Thank you so much for your help guys.
onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == UCrop.REQUEST_CROP && resultCode == RESULT_OK) {
if (data != null) {
Uri uri = UCrop.getOutput(data);
showImage(uri);
}
} else if (requestCode == PICK_IMAGE_GALLERY_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
try {
Uri sourceUri = data.getData();
File file = getImageFile();
Uri destinationUri = Uri.fromFile(file);
openCropActivity(sourceUri, destinationUri);
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),sourceUri);
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
uiHelper.toast(this, "Please select another image");
}
}
}
Crop method
private void openCropActivity(Uri sourceUri, Uri destinationUri) {
UCrop.Options options = new UCrop.Options();
options.setCropFrameColor(ContextCompat.getColor(this, R.color.colorAccent));
UCrop.of(sourceUri, destinationUri)
.withMaxResultSize(1080, 540)
.withAspectRatio(16, 9)
.start(this);
}
show ImageCropped on MainActivity
private void showImage(Uri imageUri) {
try {
File file;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
file = FileUtils.getFile(this, imageUri);
} else {
file = new File(currentPhotoPath);
}
InputStream inputStream = new FileInputStream(file);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
uiHelper.toast(this, "Please select different profile picture.");
}
}
full code MainActivity
private static final int PICK_IMAGE_GALLERY_REQUEST_CODE = 609;
public static final int ONLY_STORAGE_REQUEST_CODE = 613;
private String currentPhotoPath = "";
private UiHelper uiHelper = new UiHelper();
private ImageView imageView;
private Button vai;
Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vai = (Button)findViewById(R.id.button);
vai.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
vaiii();
}
});
findViewById(R.id.selectPictureButton).setOnClickListener(v -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
if (uiHelper.checkSelfPermissions(this))
uiHelper.showImagePickerDialog(this, this);
});
imageView = findViewById(R.id.imageView);
}
private void vaiii() {
Intent i = new Intent(this, risult.class);
// your bitmap
ByteArrayOutputStream bs = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bs);
i.putExtra("byteArray", bs.toByteArray());
startActivity(i);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == UCrop.REQUEST_CROP && resultCode == RESULT_OK) {
if (data != null) {
Uri uri = UCrop.getOutput(data);
showImage(uri);
}
} else if (requestCode == PICK_IMAGE_GALLERY_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
try {
Uri sourceUri = data.getData();
File file = getImageFile();
Uri destinationUri = Uri.fromFile(file);
openCropActivity(sourceUri, destinationUri);
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),sourceUri);
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
uiHelper.toast(this, "Please select another image");
}
}
}
private void openImagesDocument() {
Intent pictureIntent = new Intent(Intent.ACTION_GET_CONTENT);
pictureIntent.setType("image/*");
pictureIntent.addCategory(Intent.CATEGORY_OPENABLE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
String[] mimeTypes = new String[]{"image/jpeg", "image/png"};
pictureIntent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
}
startActivityForResult(Intent.createChooser(pictureIntent, "Select Picture"), PICK_IMAGE_GALLERY_REQUEST_CODE);
}
private void showImage(Uri imageUri) {
try {
File file;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
file = FileUtils.getFile(this, imageUri);
} else {
file = new File(currentPhotoPath);
}
InputStream inputStream = new FileInputStream(file);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
uiHelper.toast(this, "Please select different profile picture.");
}
}
#Override
public void onOptionSelected(ImagePickerEnum imagePickerEnum) {
if (imagePickerEnum == ImagePickerEnum.FROM_GALLERY)
openImagesDocument();
}
private File getImageFile() throws IOException {
String imageFileName = "JPEG_" + System.currentTimeMillis() + "_";
File storageDir = new File(
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM
), "Camera"
);
System.out.println(storageDir.getAbsolutePath());
if (storageDir.exists())
System.out.println("File exists");
else
System.out.println("File not exists");
File file = File.createTempFile(
imageFileName, ".jpg", storageDir
);
currentPhotoPath = "file:" + file.getAbsolutePath();
return file;
}
private void openCropActivity(Uri sourceUri, Uri destinationUri) {
UCrop.Options options = new UCrop.Options();
options.setCropFrameColor(ContextCompat.getColor(this, R.color.colorAccent));
UCrop.of(sourceUri, destinationUri)
.withMaxResultSize(1080, 540)
.withAspectRatio(16, 9)
.start(this);
}
}
Activity Result
if(getIntent().hasExtra("byteArray")) {
ImageView previewThumbnail = new ImageView(this);
Bitmap b = BitmapFactory.decodeByteArray(
getIntent().getByteArrayExtra("byteArray"),0,getIntent()
.getByteArrayExtra("byteArray").length);
star.setImageBitmap(b);
previewThumbnail.setImageBitmap(b);
}

Camera permission IOException and separation of classes [duplicate]

This question already has answers here:
Android marshmallow request permission?
(26 answers)
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 1 year ago.
I have two problems with my app. First problem is that I get an IOException:permission denied even tho I would think I have already all the permissions that I need.
The method dispatchTakePictureIntent when I run photoFile = createImageFile() triggers the permission error.
The othe problem that I have is that I want to separate all the camera-stuff and file creation-stuff to separate classes. But what is the best way to pass information/variable data between classes in a good way. Is this something I should use callbacks or observers for? I would really be glad if someone could provide a simple example of how to do this.
MainActivity:
public class MainActivity extends AppCompatActivity {
EncodeToBase64 encode = new EncodeToBase64();
String lastPhotoAsBase64;
ImageView mImageView;
ImageView mBackground;
private static int RESULT = 1;
static final int REQUEST_TAKE_PHOTO = 1;
static final int PICK_IMAGE_REQUEST = 2;
String mCurrentPhotoPath;
TextView textView;
ProgressBar progress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, RESULT);
}
setContentView(R.layout.activity_main);
mImageView = findViewById(R.id.imageView);
mBackground = findViewById(R.id.backgroundImage);
Button cameraButton = findViewById(R.id.cameraButton);
Button galleryButton = findViewById(R.id.galleryButton);
textView = findViewById(R.id.textView);
progress = findViewById(R.id.progressBar);
cameraButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
galleryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
try {
setPic();
} catch (IOException e) {
e.printStackTrace();
}
} else if (requestCode == PICK_IMAGE_REQUEST && data.getData() != null) {
Uri selectedImage = data.getData();
try {
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
mCurrentPhotoPath = picturePath;
cursor.close();
setPic();
} catch (IOException e) {
e.printStackTrace();
}
}
}
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 = getExternalStoragePublicDirectory(DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
galleryAddPic();
return image;
}
private static int exifToDegrees(int exifOrientation) {
if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) {
return 90;
} else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {
return 180;
} else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) {
return 270;
}
return 0;
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
public void setPic() throws IOException {
// Get the dimensions of the View
int targetW = mImageView.getWidth();
int targetH = mImageView.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
//BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
ExifInterface exif = new ExifInterface(mCurrentPhotoPath);
int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int rotationInDegrees = exifToDegrees(rotation);
//int deg = rotationInDegrees;
Matrix matrix = new Matrix();
if (rotation != 0f) {
matrix.preRotate(rotationInDegrees);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
lastPhotoAsBase64 = encode.encode(bitmap);
if (lastPhotoAsBase64 != null) {
new postData().execute(lastPhotoAsBase64);
} else {
Toast.makeText(MainActivity.this, "No base64 data found!", Toast.LENGTH_LONG).show();
}
mImageView.setImageBitmap(bitmap);
}
public 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
ex.printStackTrace();
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
public class postData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... strings) {
HttpConnectionActivity hh = new HttpConnectionActivity();
String temp = hh.HttpConnection(strings[0]);
return temp;
}
#Override
protected void onPreExecute() {
textView.setVisibility(View.INVISIBLE);
progress.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String s) {
progress.setVisibility(View.INVISIBLE);
JSONObject jsonRaw = null;
String age = null;
String gender = null;
String result = null;
if(!(s.contains("5002"))) {
try {
jsonRaw = new JSONObject(s);
age = jsonRaw.getJSONArray("images").getJSONObject(0).getJSONArray("faces").getJSONObject(0).getJSONObject("attributes").getString("age");
gender = jsonRaw.getJSONArray("images").getJSONObject(0).getJSONArray("faces").getJSONObject(0).getJSONObject("attributes").getJSONObject("gender").getString("type");
result = "Du är en " + ((gender.equals("M")) ? "Man" : "Kvinna") + " som är " + age + " år gammal";
} catch (JSONException e) {
e.printStackTrace();
}
}
else{
result = "Inga ansikten hittades";
}
textView.setText(result);
textView.setVisibility(View.VISIBLE);
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.cliff.camera2">
<uses-feature android:name="android.hardware.camera"
android:required="true" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.android.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths"></meta-data>
</provider>
</application>
</manifest>
file_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="DCIM/SkitApp" />
</paths>
The CAMERA permission is a dangerous permission, so is WRITE_EXTERNAL_STORAGE. Starting in API 23 you have to request these permissions at runtime. Meaning even though you list it in the manifest, for API >= 23 you have to request them

Not able to upload image from camera in android

I am working on an app in which I want to get image from gallery or camera and then send it to server using multipart. I am able to send picture from gallery to server but when I tried to send image from camera it shows me failure.
// code for the same
// code fro open camera
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
// on activity result
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CAMERA) {
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");
Log.d("TAG", "onActivityResult: "+Uri.fromFile(destination));
filePath = destination.toString();
if (filePath != null) {
try {
execMultipartPost();
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getActivity(), "Image not capturd!", Toast.LENGTH_LONG).show();
}
}
// send to server code
private void execMultipartPost() throws Exception {
File file = new File(filePath);
String contentType = file.toURL().openConnection().getContentType();
Log.d("TAG", "file new path: " + file.getPath());
Log.d("TAG", "contentType: " + contentType);
RequestBody fileBody = RequestBody.create(MediaType.parse(contentType), file);
final String filename = "file_" + System.currentTimeMillis() / 1000L;
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("date", "21-09-2017")
.addFormDataPart("time", "11.56")
.addFormDataPart("description", "hello")
.addFormDataPart("image", filename + ".jpg", fileBody)
.build();
Log.d("TAG", "execMultipartPost: "+requestBody);
okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://myexample/api/user/lets_send")
.post(requestBody)
.build();
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, final IOException e) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity(), "nah", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onResponse(Call call, final okhttp3.Response response) throws IOException {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
try {
Log.d("TAG", "response of image: " + response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
});
}
Try This, it may help
Intent takePhotoIntent= new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Date date = new Date();
String timeStamp = new SimpleDateFormat(pictureNameDateFormat, Locale.US).format(date.getTime());
File fileDirectory = new File(Environment.getExternalStorageDirectory() + "/Pictures");
if (fileDirectory.exists()) {
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(
new File(Environment.getExternalStorageDirectory() + "/Pictures/picture_"+ timeStamp + ".png")));
takePhotoIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
takePhotoIntent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
if (takePhotoIntent.resolveActivity(activity.getPackageManager()) != null) {
activity.startActivityForResult(takeVideoIntent, captureVideoActivityRequestCode);
}
}
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();
}
Log.e("path",Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
}
Please use below code to capture image by camera and for pick image from gallery and you can crop also.
First of all please add this dependency in your build.gradle
compile 'com.theartofdev.edmodo:android-image-cropper:2.3.+'
In your Activity please add this code :
uploadPic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onSelectImageClick(view);
}
});
/**
* Start pick image activity with chooser.
*/
public void onSelectImageClick(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(AccountSettingActivity.this, android.Manifest.permission.CAMERA) + ContextCompat.checkSelfPermission(AccountSettingActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(AccountSettingActivity.this, new String[]{android.Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, MY_REQUEST_CAMERA);
} else if (ContextCompat.checkSelfPermission(AccountSettingActivity.this, android.Manifest.permission.CAMERA) + ContextCompat.checkSelfPermission(AccountSettingActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
CropImage.startPickImageActivity(this);
}
}else {
CropImage.startPickImageActivity(this);
}
}
#Override
#SuppressLint("NewApi")
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// handle result of pick image chooser
if (requestCode == CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Uri imageUri = CropImage.getPickImageResultUri(this, data);
startCropImageActivity(imageUri);
}
// handle result of CropImageActivity
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
fileUri = result.getUri();
userImage.setImageURI(result.getUri());
Toast.makeText(this, "Cropping successful, Sample: " + result.getSampleSize(), Toast.LENGTH_LONG).show();
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Toast.makeText(this, "Cropping failed: " + result.getError(), Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED ) {
CropImage.startPickImageActivity(this);
} else {
Toast.makeText(this, "Cancelling, required permissions are not granted", Toast.LENGTH_LONG).show();
}
}
/**
* Start crop image activity for the given image.
*/
private void startCropImageActivity(Uri imageUri) {
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setMultiTouchEnabled(true)
.start(this);
}
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
in manifest please add these permissions and ask for run time permissions also ,this may solve your problem ,Your coding is correct those works for me perfectly after adding permission.
Please go trough the following code
try {
if (imageUri != null) {
photo = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(imageUri));
} else {
photo = (Bitmap) data.getExtras().get("data");
}
Uri tempUri = CommonData.getImageUri(getContext(), photo);
uri = tempUri.toString();
String path = CommonData.convertImageUriToFile(tempUri, getActivity());
// new PreprocessImagesTask().execute(path);
showLoader();
new ProcessingImage(this).execute(path);
} catch (Exception e) {
e.printStackTrace();
}
public static Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public static String convertImageUriToFile(Uri imageUri, Activity activity) {
String imgPath = "";
String Path;
try {
Cursor cursor = null;
int imageID = 0;
try {
/* ********** Which columns values want to get ****** */
String[] proj = {
MediaStore.Images.Media.DATA,
MediaStore.Images.Media._ID,
MediaStore.Images.Thumbnails._ID,
MediaStore.Images.ImageColumns.ORIENTATION
};
cursor = activity.getContentResolver().query(
imageUri, // Get data for specific image URI
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null // Order-by clause (ascending by name)
);
int file_ColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
int size = cursor.getCount();
/* ****** If size is 0, there are no images on the SD Card. **** */
if (size == 0) {
// imageDetails.setText("No Image");
} else {
int thumbID = 0;
if (cursor.moveToFirst()) {
Path = cursor.getString(file_ColumnIndex);
//String orientation = cursor.getString(orientation_ColumnIndex);
String CapturedImageDetails = " CapturedImageDetails : \n\n"
+ " ImageID :" + imageID + "\n"
+ " ThumbID :" + thumbID + "\n"
+ " Path :" + Path + "\n";
showLog("CapturedImageDetails", CapturedImageDetails);
imgPath = Path;
// Show Captured Image detail on view
// imageDetails.setText(CapturedImageDetails);
}
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return "" + imgPath;
} catch (IllegalArgumentException e) {
e.printStackTrace();
return "";
}
}
Give a try!
private static final int REQUEST_IMAGE = 100;
private static final String TAG = "MainActivity";
TextView imgPath;
ImageView picture;
File destination;
String imagePath;
//onCreate
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(destination));
startActivityForResult(intent, REQUEST_IMAGE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if( requestCode == REQUEST_IMAGE && resultCode == Activity.RESULT_OK ){
try {
FileInputStream in = new FileInputStream(destination);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 10;
imagePath = destination.getAbsolutePath();//get your path
imgPath.setText(imagePath);
Bitmap bmp = BitmapFactory.decodeStream(in, null, options);
picture.setImageBitmap(bmp);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
else{
imgPath.setText("Request cancelled");
}
}

how can i store gallery image in application directory

i have got the image directly from the camera , gallery to the image view in my app its all working fine.
Now what I want is to save this image from Image View to the application directory and also access it when required.
//You Can try This
File myDir = new File(Environment.getExternalStorageDirectory().toString() + "/yourDirectoryname");
myDir.mkdirs();
File file = new File(myDir, yourImagePath);
if (file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
imgBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
public class EditProfile extends AppCompatActivity {
ImageView imageView;
EditText Name,Email,MobileNo;
public static int count = 0;
String loginid;
Bitmap bitmap;
private static final int CAMERA_REQUEST = 1888;
String picturePath;
static int i=0;
private final int CAMERA_RESULT = 1;
private final String Tag = getClass().getName();
byte[] image = null;
Button button1;
static File out;
String path1;
ImageView imageView1;
Bitmap photo ;
byte[] b=null;
Button EditProfile;
String Username;
String name;
String email;
String Imgpath;
String Imgpath1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
EditProfile=(Button)findViewById(R.id.edit_profile);
Imgpath=getSharedPreferences("Bytearray",0).getString("Bytearray",null);
Imgpath1=getSharedPreferences("uri",0).getString("uri",null);
imageView=(ImageView)findViewById(R.id.profile_photo);
EditProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectImage();
}
});
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(EditProfile.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
PackageManager pm = getPackageManager();
if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, MyFileContentProvider.CONTENT_URI);
startActivityForResult(i, CAMERA_RESULT);
} else {
Toast.makeText(getBaseContext(), "Camera is not available", Toast.LENGTH_LONG).show();
}
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == CAMERA_RESULT) {
out = new File(getFilesDir(), "newImage.jpg");
if(!out.exists()) {
Toast.makeText(getBaseContext(),
"Error while capturing image", Toast.LENGTH_LONG)
.show();
return;
}
Bitmap mBitmap = BitmapFactory.decodeFile(out.getAbsolutePath());
String path=out.getAbsolutePath();
getSharedPreferences("path",0).edit().putString("path",path).commit();
imageView.setImageBitmap(mBitmap);
}
else if (requestCode == 2) {
imageView.setImageURI(selectedImage);
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
// imageView.setImageBitmap(yourSelectedImage);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourSelectedImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Bitmap image=BitmapFactory.decodeByteArray(byteArray,0,byteArray.length);
imageView.setImageBitmap(image);
}
}
}
Initiate the camera intent like this by creating a file of known path,and after the image capture Your image appears in that path:
Uri capturedImageUri;//global variable
private void initiateImageCapture() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
capturedImageUri = Uri.fromFile(photoFile);
} catch (IOException e) {
e.printStackTrace();
}
if (photoFile == null || capturedImageUri == null) {
Utils.showLongToast(getActivity(), "error");
} else {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, capturedImageUri);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null)
startActivityForResult(takePictureIntent, Constants.INTENT_IMAGE_CAPTURE);
else
Utils.showLongToast(getActivity(), "try again);
}
}
}
private File createImageFile() throws IOException {
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 */
);
return image;
}

How to see camera app take photo asynchronous in the gallery

I am working on a basic camera app. I can take a photo, and I can see it in my app. But I want to see my photo in gallery asynchronous. When restart the phone, I can see my photo in the gallery.
Sample code.
public class PhotosActivity extends Fragment implements View.OnClickListener {
private final int REQUEST_CODE = 100;
private Button fotobutton;
private ImageView foto_image;
private static final String IMAGE_DIRECTORY_NAME = "OlkunMustafa";
public static final int MEDIA_TYPE_IMAGE = 1;
private Uri fileUri;
// Directory name to store captured images and videos
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.photos_activity,container,false);
fotobutton = (Button) rootView.findViewById(R.id.fotobutton);
foto_image = (ImageView) rootView.findViewById(R.id.foto_image);
fotobutton.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
if( v == fotobutton) {
Intent photo_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFile(MEDIA_TYPE_IMAGE);
photo_intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(photo_intent,100);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == getActivity().RESULT_OK)
{
BitmapFactory.Options options = new BitmapFactory.Options();
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
foto_image.setImageBitmap(bitmap);
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = getOutputMediaFile(MEDIA_TYPE_IMAGE);
mediaScanIntent.setData(contentUri);
getActivity().sendBroadcast(mediaScanIntent);
}
}
private static Uri getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStorageDirectory(),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
}
else {
return null;
}
return Uri.fromFile(mediaFile);
}
}
How can I do it?
You need to call a broadcast to tell Android OS that you have added an Image
First Method
private void galleryAddPic()
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File("file://"+ Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES));
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
else
{
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}
}
Second Method
Or Call
ctx.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,Uri.parse("file://" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES))));
Also have a look on this answer
you can use this method to store image file on media store provider:
public static void addImageToGallery(final String filePath, final Context context) {
ContentValues values = new ContentValues();
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.MediaColumns.DATA, filePath);
context.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
}
And ScanListener
You can directly save image to Gallery
MediaStore.Images.Media.insertImage(getContentResolver(), yourBitmap, yourTitle , yourDescription);
Try using this logic :
private static int TAKE_PICTURE = 1;
private Uri imageUri;
public void takePhoto(View view) {
Intent intent = new Intent("android.media.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());
}
}
}
}

Categories

Resources