I'm making an Android application in Android studio where the user can take a photo and save it into a new folder in their gallery. Currently the application takes the pictures fine but doesn't save the image into the new "SOC" folder in my gallery. I'm not getting any errors and I have no idea why it's not saving the image. Any help would be appreciated.
My code is as fallows
static final int REQUEST_IMAGE_CAPTURE = 1;
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 0;
public void onClickbtnCamera(View v)
{
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
Uri uriSavedImage=Uri.fromFile(new File("/storage/emulated/0/DCIM/SOC","QR_"+timeStamp+ ".png"));
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(imageIntent, 1);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
//Check for succesful result code
if (resultCode == -1) {
//Show your Toast when the result is a success.
Toast toast = Toast.makeText(getApplicationContext(),
"Picture is saved in your SOC gallery", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 100, 0);
toast.show();
}
}
}
I think you must manually add your new photo Uri to Media Content Provider.
take a look here
Call this method in your Activity for result
protected void addPhotoToGallery() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(getCurrentPhotoPath());
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.getActivity().sendBroadcast(mediaScanIntent);
}
you should save the photo path before launching the intent and then getCurrentPhotoPath() must get that path
Related
I get pictures url from gallery or camera on android but I can't convert them to file. When i developing an app with Java in android, sometimes I need to get pictures from gallery and camera to my application. But when i try to do this I'm getting errors.
Isn't there a standard here? The code works at one api level and does not works another one. Or when I take the URI of some images and convert it to file, I get an error regardless of the api level. I wonder if there is a fundamental solution to this problem?
I am starting intent with this
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,IMAGE_RESULT);
And then I'm catching data with this code:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == IMAGE_RESULT) {
String filePath = ImageFilePath.getPath(OwnProfileActivity.this, data.getData());
selectedFile = new File(filePath);
showProgressDialog();
Handler handler = new Handler();
handler.postDelayed(this::chaneProfileImage, 1000);
}
}
}
May I suggest something like this, but of course this is if you have a bitmap:
private fun getImageUriFromBitmap(image: Bitmap): Uri? {
val bytes = ByteArrayOutputStream()
image.compress(Bitmap.CompressFormat.PNG, 100, bytes)
val relativeLocation = Environment.DIRECTORY_PICTURES + File.pathSeparator + "NotifyMe"
val contentValues = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, "notifyMe_${System.currentTimeMillis()}")
put(MediaStore.MediaColumns.MIME_TYPE, "image/png")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
put(MediaStore.MediaColumns.RELATIVE_PATH, relativeLocation)
put(MediaStore.MediaColumns.IS_PENDING, 1)
}
}
return context?.contentResolver?.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
}
Then you can create the file with the uri
val file = File(uri.path)
source: https://gist.github.com/franciscobarrios/9f6634c87ca6e56ed70cd96807dd1dcb
i'm writing an android app on java and need to let my users select and crop images from the gallery.
There is no problem when choosing an image from any native gallery, but when a user chooses to eater crop or choose an image from google photos app the app crushes.
I cannot figure out what is the source of the problem so any answer will be helpful
this is the code i'm using
class fields:
private Uri imageUri;
opening the camera:
private void camOpen() {
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(Environment.getExternalStorageDirectory(), "file" + String.valueOf(System.currentTimeMillis()) + ".png");
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
imageUri = Uri.fromFile(f);
i.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
i.putExtra("return-data", true);
startActivityForResult(i, CAMERA_CODE);
}
opening the gallery:
private void galleryOpen() {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(i, "select file"), SELECT_PHOTO_CODE);
}
cropping the image:
private void cropImage() {
try {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(imageUri, "image/*");
cropIntent.putExtra("crop", true);
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, CROP_CODE);
} catch (Exception e) {}
}
the result handler:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_CODE && resultCode == Activity.RESULT_OK) {
cropImage();
} else if (requestCode == SELECT_PHOTO_CODE && resultCode == Activity.RESULT_OK) {
if (data != null) {
imageUri = data.getData();
cropImage();
}
} else if (requestCode == CROP_CODE && resultCode == Activity.RESULT_OK) {
Bundle bundle = data.getExtras();
Bitmap b = bundle.getParcelable("data");
hasImageChanged=true;
ivProfilePic.setImageBitmap(b);
capturedImage = b;
}
}
thank you for any useful help...
Android does not support crop intent because croping is not part of android api.
So i recommend you for Using library
the issue was with the crop intent. I ended up using the uCrop library and it fixed the problem.
I'm currently working on the user profile for my app. Up until recently, I've been testing on a Samsung Galaxy Note 4, which hasn't been giving me any problems with the code below. In later testing, however, I got my hands on a Nexus 5x, and when I use the below code to try and select a user profile image, I get the error "Unfortunately Photos has stopped". I don't have any error logs, since I am unable to debug Photos.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case 0:
if(resultCode == RESULT_OK){
Uri selectedImage = data.getData();
cropImage(selectedImage);
}
break;
case 1:
if(resultCode == RESULT_OK){
Uri selectedImage = data.getData();
cropImage(selectedImage);
}
break;
case 2:
if(resultCode == RESULT_OK){
Uri selectedImage = data.getData();
profileImage.setImageURI(selectedImage);
try {
userProfileImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
AlmightyFunctions.ImageService.saveProfileImage(user,userProfileImage);
}
catch (IOException e) {
e.printStackTrace();
}
}
break;
}
}
public void showImageSelectDialog() {
CharSequence options[] = new CharSequence[] {
getString(R.string.select_camera),
getString(R.string.select_gallery)
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.select_image_dialog));
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
MarshMallowPermission mmp = new MarshMallowPermission(UserProfileActivity.this);
switch(which) {
case 0:
if (!mmp.checkPermissionForCamera()) {
mmp.requestPermissionForCamera();
}
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);
break;
case 1:
if (!mmp.checkPermissionForExternalStorage()) {
mmp.requestPermissionForExternalStorage();
}
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, 1);
break;
}
}
});
builder.show();
}
public void cropImage(Uri photoUri) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(photoUri, "image/*"); // this will open all images in the Gallery
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1); // this defines the aspect ration
intent.putExtra("aspectY", 1);
intent.putExtra("return-data", true); // true to return a Bitmap, false to directly save the cropped iamge
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri); //save output image in uri
startActivityForResult(intent,2);
}
Any help would be greatly appreciated.
Android does not have a CROP Intent. Your code will fail on hundreds of millions of devices.
There are many image cropping libraries available for Android. Please use one.
I have made an application where the user can take a photo and save it into their gallery in a separate folder named "SOC". This works on one of my Android devices however on the other device the user can take the picture but the image doesn't save for some reason. The device the image saves on is Android 4.2 the device it does not save the image on is Android 5.0 not sure if this has anything to do with it.
My Code is as fallows
static final int REQUEST_IMAGE_CAPTURE = 1;
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 0;
public void onClickbtnCamera(View v)
{
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
Uri uriSavedImage = Uri.fromFile(new File("/storage/emulated/0/DCIM/SOC","QR_"+timeStamp+ ".png"));
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(imageIntent, 1);
}
#Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
if (requestCode == 1) {
//Check for succesful result code
if (resultCode == -1) {
//Show your Toast when the result is a success.
Toast toast = Toast.makeText(getApplicationContext(),
"Picture is saved in your SOC gallery", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 100, 0);
toast.show();
}
}
}
I am making an app that will let users take photos and save them to the app, which will be password protected. So far, the app can take a picture, retrieve it, and set it to an image view. However, when I restart the app the image goes away. How can I save it?
int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 0;
Uri imageUri;
public void takePic(View view){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "filename_" +
String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra("data", imageUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
Bundle extras = data.getExtras();
Log.e("URI", imageUri.toString());
Bitmap bmp = (Bitmap) extras.get("data");
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageBitmap(bmp);
}
else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT);
}
}
}
That imageUri you pass to the Intent- the image file is saved there. Just save the URI in SharedPreferences or other persistant storage and check that storage next time you launch your app.
This code is working on me :
private void takePicture() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
mImageCaptureUri = null;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
mImageCaptureUri = Uri.fromFile(mFileTemp);
}
else {
mImageCaptureUri = InternalStorageContentProvider.CONTENT_URI;
}
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
intent.putExtra("return-data", true);
startActivityForResult(intent, REQUEST_CODE_TAKE_PICTURE);
} catch (Exception e) {
Log.d("error", "cannot take picture", e);
}
}
This is how to define mFileTemp
String state = Environment.getExternalStorageState();
File mFileTemp;
if (Environment.MEDIA_MOUNTED.equals(state)) {
//this is like that
//any folder name/you can add inner folders like that/your photo name122412414124.jpg
mFileTemp = new File(Environment.getExternalStorageDirectory()+File.separator+"any folder name"+File.separator+"you can add inner folders like that"
, "your photo name"+System.currentTimeMillis()+".jpg");
mFileTemp.getParentFile().mkdirs();
}
else {
mFileTemp = new File(getFilesDir()+"any folder name"+
File.separator+"myphotos")+File.separator+"profilephotos", "your photo name"+System.currentTimeMillis()+".jpg");
mFileTemp.getParentFile().mkdirs();
}
Your global variables
private Uri mImageCaptureUri;
private File mFileTemp;
1) Define your global variables
2) Then define mFileTemp
3)Then trigger takePicture() method