android - saving a picture from user's gallery - android

Here is my code. I'm having problems with showing and saving the pic picked from the user's gallery, whilst when I do it from the camera it works just fine for me.
here is how the user is reffered to his gallery-
if (v.getId() == R.id.btnAddDucuments) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setMessage("to add documents");
alertDialog.setPositiveButton("from camera", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// user choose to take a picture
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAM_REQUEST);
}
});
alertDialog.setNegativeButton("from gallery", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// user choose to pick a photo from gallery
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI), GET_FROM_GALLERY); }
});
alertDialog.show();
and here is how the picture is supposed to be saved. I need it both as a String (so I can use it further on) and in the ImageView that is in this avtivity (named imgTheDocument).
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==GET_FROM_GALLERY && resultCode == Activity.RESULT_OK) {
Uri selectedImage = data.getData();
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
StringImgDocument = BitMapToString(bitmap);
imgTheDocument.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
When I run this code the activity stops after pressing on the wanted picture. I can't understand where is the problem. I have used this code before and it worked just fine.
I'll appriciate any help!! Thanks:)
my manifest permissions:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

the intent to pick image(This is Error free and works on all android versions!)
Intent intent;
if (Build.VERSION.SDK_INT < 19){
intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, GET_FROM_GALLERY);
} else {
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, GET_FROM_GALLERY);
}
This is for onActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==GET_FROM_GALLERY && resultCode == Activity.RESULT_OK) {
//you can both use the selectedImageUri or yourSelectedImagePath for working the Image you picked,send it somewhere or store it in database or etc..
Uri selectedImageUri = data.getData();
String yourSelectedImagePath = selectedImage.tostring;
//I just use the Uri to display the selected image in an imageview
yourImageView.setImageUri(selectedImage);
}

Related

Gallery permission and Camera Permission not working

i was adding profile picture option in my application from camera and gallery All was working well till i tried to select a picture and display it in my image circulerView .when i select a picture to set in my imageCirculerView , it doesn't set in the imageCirculerView and no error is even showing ..So i literally don't know where i did the mistake
private void pickFromGallery() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"select picture"), IMAGE_PICK_GALLERY_CODE);
}
private void pickFromCamera() {
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.Images.Media.TITLE, "Temp_image Title");
contentValues.put(MediaStore.Images.Media.DESCRIPTION, "Temp_desc Desctription");
image_uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(intent, IMAGE_PICK_CAMERA_CODE);
}
profilepicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//pick a image
showImagePickDialog();
}
});
private void showImagePickDialog() {
//options to display in dialoge
String[] options = {"Camera", "Dialoge"};
//dialoge
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick Image").setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
//Camera Clicked
if (checkCameraPermission()) {
//Camera request allowed
pickFromCamera();
} else {
//not allowed Request
requestCameraPermission();
}
} else {
//gallery Clicked
if (checkStoragePermission()) {
//Storage request allowed
pickFromGallery();
} else {
//not allowed Request
requestStoragePermission();
}
}
}
}).show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode == RESULT_OK){
if(requestCode== IMAGE_PICK_GALLERY_CODE){
//getPicked image
image_uri = data.getData();
//settoimageView
profilepicture.setImageURI(image_uri);
}else if(requestCode== IMAGE_PICK_CAMERA_CODE){
//settoimageView
profilepicture.setImageURI(image_uri);}
}
super.onActivityResult(requestCode, resultCode, data);
}

How to Upload Image from Camera to Server instead of image chooser

How can i upload images from camera to my web server ,
I was able to upload using image chooser like in this tuto
https://www.simplifiedcoding.net/android-upload-image-to-server/
, but i would like to choose images from camera and galery instead
public void uploadMultipart() {
//getting the actual path of the image
String path = getPath(filePath);
//Uploading code
try {
String uploadId = UUID.randomUUID().toString();
//Creating a multi part request
new MultipartUploadRequest(this, uploadId, Constants.UPLOAD_URL)
.addFileToUpload(path, "image") //Adding file
.addParameter("name", name) //Adding text parameter to the request
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload(); //Starting the upload
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
}
//method to show file chooser
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
//handling the image chooser activity result
#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) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I also found this method , but it didn't work for me
How can replace the file chooser method in the above code properly to get the image path and name , and then upload it as in the tuto
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(UploadImageTest.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"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
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();
}
For Uploading a captured image to the server the whole your code remains the same you just need to pass your captured image file path into your uploadMultipart function.
You will get captured image file path in your onActivityResult.

Get Image from the Gallery and Show in ImageView

I need to get an image from the gallery on a button click and show it into the imageview.
I am doing it in the following way:
btn_image_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getImageFromAlbum();
}
});
The method Definition is as:
private void getImageFromAlbum(){
try{
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}catch(Exception exp){
Log.i("Error",exp.toString());
}
}
The activity result method is
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
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 picturePath = cursor.getString(columnIndex);
cursor.close();
try {
bmp = getBitmapFromUri(selectedImage);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
image_view.setImageBitmap(bmp);
//to know about the selected image width and height
Toast.makeText(MainActivity.this, image_view.getDrawable().getIntrinsicWidth()+" & "+image_view.getDrawable().getIntrinsicHeight(), Toast.LENGTH_SHORT).show();
}
}
The Problem
The problem I am facing is when the image resolution is high suppose that if the image size is of 5mp to 13mp. It won't loads up and show up into the image view.
But the images with the low width and height are successfully loading into the image view!
Can somebody tell me any issues with the code and what I am doing wrong? I just want to import the camera images from the gallery and show them in the image view!
you can try this.
paste this code in your button click event.
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, RESULT_LOAD_IMG);
and below code is your on activity result
#Override
protected void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
if (resultCode == RESULT_OK) {
try {
final Uri imageUri = data.getData();
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
image_view.setImageBitmap(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(PostImage.this, "Something went wrong", Toast.LENGTH_LONG).show();
}
}else {
Toast.makeText(PostImage.this, "You haven't picked Image",Toast.LENGTH_LONG).show();
}
}
I hope it is helpful for you.
I use this code:
This code used to start gallery activity.
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, GALLERY_REQUEST);
And get the result in:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_OK)
switch (requestCode){
case GALLERY_REQUEST:
Uri selectedImage = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), selectedImage);
carImage.setImageBitmap(bitmap);
} catch (IOException e) {
Log.i("TAG", "Some exception " + e);
}
break;
}
}
And don't forget to declare permission in AndroidManifest.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Because OnActivityResult method is deprecated, proper way nowadays with AndroidX Activity, is Activity Result APIs, and that recommended way, see docs
"registerForActivityResult() takes an ActivityResultContract and an ActivityResultCallback and returns an ActivityResultLauncher which you’ll use to launch the other activity."
ActivityResultLauncher<String> mGetContent = registerForActivityResult(new ActivityResultContracts.GetContent(),
new ActivityResultCallback<Uri>() {
#Override
public void onActivityResult(Uri uri) {
previewImage.setImageURI(uri);
}
});
And simply call
mGetContent.launch("image/*");
when needed.
startActivityForResult() is deprecated. Android introduced Activity Result Api for same purpose.
This is how to implement Activity Result
ActivityResultLauncher<Intent> imagePickerActivityResult = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result != null) {
Uri imageUri = result.getData().getData();
Glide.with(this)
.load(imageUri)
.into(R.id.profileImageView);
}
}
}
);
Call above code by calling launch() with intent
Intent galleryIntent = new Intent(Intent.ACTION_PICK);
galleryIntent.setType("image/*");
imagePickerActivityResult.launch(galleryIntent);
I try all the solutions above but they don't work for me . I saw a code from tutorialspoint website and it works for me very well this is the code :
final int PICK_IMAGE = 100;
Button button = findViewById(R.id.button33);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent gallery = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, PICK_IMAGE);
}
});
#Override
protected void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
Uri imageUri;
ImageView imageView = findViewById(R.id.image_main_galary);
if (resultCode == RESULT_OK && reqCode == 100){
imageUri = data.getData();
imageView.setImageURI(imageUri);
}
}
the most important issue : don't forget PERMISSION :
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

No Activity found to handle Intent act=com.android.camera.action.CROP

I'm trying to implement a function to pick a photo from android built-in gallery (not from SD card) or taking a photo using camera. After the image is picked it will be cropped by the user. An ImageView will also be updated with the cropped image. Now after picking an image from gallery, I cannot crop it -- "No Activity found to handle Intent act=com.android.camera.action.CROP" error was returned. And I also can't seem to update the ImageView with the selected image. Can someone please tell me what was wrong? Thanks.
My code is as follows:
private void ShowPickDialog() {
new AlertDialog.Builder(this)
.setTitle("Add Photo")
.setNegativeButton("Select from Photos", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),3);
}
})
.setPositiveButton("Take a Pic", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri
.fromFile(new File(Environment.DIRECTORY_PICTURES,
"image.jpg")));
startActivityForResult(intent, 2);
}
}).show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 1:
startPhotoZoom(data.getData());
break;
case 2:
File temp = new File(Environment.getExternalStorageDirectory()
+ "/test.jpg");
startPhotoZoom(Uri.fromFile(temp));
break;
case 3:
if(data != null){
setPicToView(data);
}
break;
default:
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
public void startPhotoZoom(Uri uri) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 150);
intent.putExtra("outputY", 150);
intent.putExtra("return-data", true);
startActivityForResult(intent, 3);
}
private void setPicToView(Intent picdata) {
Bundle extras = picdata.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
//update ImageView with selected image
mPic.setImageBitmap(photo);
}
}
Android Does Not Have a Crop Intent
you can use libraries instead
Android CropImage

rHow do you modify this function to return an image path?

So I found a function that would prompt the use to open the gallery of the device. But upon searching around I couldn't find anything that would help me modify this to return an image path. They say something about onActivityResult() which I put on the void itself and is then rejected. Any help on this?
public void chooser() {
AlertDialog.Builder myDialog
= new AlertDialog.Builder(IPAddress.this);
myDialog.setTitle("Import Menu Images");
LinearLayout layout = new LinearLayout(IPAddress.this);
layout.setOrientation(LinearLayout.VERTICAL);
myDialog.setView(layout);
myDialog.setPositiveButton("Open Folder", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
Intent i = new Intent(
Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 1);
}
});
myDialog.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
arg0.dismiss();
}
});
myDialog.show();
}
I would like it to return the path of the image selected and then I would use that path to copy the said file and save it to a directory I have created on OnCreate of the activity.
Also, I can't seem to be able to debug the said function as when I click the "Open Folder" button, it would give an error saying
The application Camera(process.com.android.gallery) has stopped unexpectedly. Please try again.
which I've tried multiple times. I even added a front camera to the emulator.
The function is called here :
Button menu_image = (Button) findViewById(R.id.menu_image);
menu_image.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View arg0) {
chooser();
}
});
So I would like the chooser to return a string(?) type if it is possible which I would then use to File Copy and then rename.
A default app chooser can be queried by following way.
Button galleryBtn = (Button) view.findViewById(R.id.gallery_btn);
galleryBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select Picture"), 2);
}
});
And you'll receive the selected file's URi in onActivityResult() of your activity/fragment.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri uriString = null;
if (requestCode == 2 && resultCode == RESULT_OK) {
Uri uri = data.getData();
if (uri != null) {
Cursor cursor = getActivity().getContentResolver()
.query(uri,
new String[] { android.provider.MediaStore.Images.ImageColumns.DATA },
null, null, null);
cursor.moveToFirst();
Bitmap bm = BitmapFactory.decodeFile(cursor.getString(0));
File file = new File(cursor.getString(0));
uriString = Uri.fromFile(file);
// do processing with the uri here
cursor.close();
}
}else{
Log.e("RDT", "Something went wrong.");
return;
}
}

Categories

Resources