Set two cropped image from camera separately in image view (Android Studio) - java

I am try to take two image from camera and crop image then show cropped image in two Imageview separately.
I have 2 Button to open camera one for capture first image then cropped to display it in Imageview and the second do the same thing.
My code in MainActivity
variable in calss
static int CAMERA_REQUEST_CODE = 228;
static int CAMERA_REQUEST_CODE1 = 229;
Uri pictureUri = null;
ImageView iv, iv1;
Button bt, bt1;
onCreate method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = findViewById(R.id.iv);
bt = findViewById(R.id.bt);
iv1 = findViewById(R.id.iv1);
bt1 = findViewById(R.id.bt1);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
invokeCamera();
}
});
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
invokeCamera1();
}
});
}
invokeCamera() and invokeCamera1() function
public void invokeCamera() {
// get a file reference
pictureUri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName(), createImageFile()); // Make Uri file example file://storage/emulated/0/Pictures/Civil_ID20180924_180619.jpg
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // Go to camera
// tell the camera where to save the image.
intent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);
// tell the camera to request WRITE permission.
intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
public void invokeCamera1() {
// get a file reference
pictureUri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName(), createImageFile()); // Make Uri file example file://storage/emulated/0/Pictures/Civil_ID20180924_180619.jpg
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // Go to camera
// tell the camera where to save the image.
intent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);
// tell the camera to request WRITE permission.
intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivityForResult(intent, CAMERA_REQUEST_CODE1);
}
createImageFile() function
// To create image file in pictures directory
public File createImageFile() {
// the public picture director
File picturesDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); // To get pictures directory from android system
// timestamp makes unique name.
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String timestamp = sdf.format(new Date());
// put together the directory and the timestamp to make a unique image location.
File imageFile = new File(picturesDirectory, timestamp + ".jpg");
return imageFile;
}
onActivityResult function
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK) // resultCode: -1
{
if(requestCode == CAMERA_REQUEST_CODE ) // requestCode: 288
{
Uri picUri = pictureUri;
startCropImageActivity(picUri);
Toast.makeText(MainActivity.this, "Image 1 save",
Toast.LENGTH_SHORT).show();
}
if(requestCode == CAMERA_REQUEST_CODE1)
{
Uri picUri = pictureUri;
startCropImageActivity(picUri);
Toast.makeText(MainActivity.this, "Image 2 save",
Toast.LENGTH_SHORT).show();
}
}
if(requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK)
{
Croppedimage(result, iv); // my problem !
/*
* Here i want to use if or switch statement to can use iv1
for second camera button! HOW?
*
* example
*
* if(for first camera button)
* {
* Croppedimage(result, iv);
* }
*
* if(for second camera button)
* {
* Croppedimage(result, iv1);
* }
*
* */
}
else if(resultCode ==
CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE)
{
// if there is any error show it
Exception error = result.getError();
Toast.makeText(this, "" + error, Toast.LENGTH_LONG).show();
}
}
}
startCropImageActivity function
private void startCropImageActivity(Uri imageUri) {
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setMultiTouchEnabled(true)
.start(this);
}
Croppedimage function
public void Croppedimage(CropImage.ActivityResult result,ImageView iv)
{
Uri resultUri = null; // get image uri
if (result != null) {
resultUri = result.getUri();
}
//set image to image view
iv.setImageURI(resultUri);
}
____________________________________________________________________________
The problem
The cropped image for second Button set in first Imageview.
Need to find way to reach to iv1 in onActivityResult for second camera Button.
Any suggestions?
Library use for crop image
THANKS.

Looking in the issues on the GitHub respository I found this one, that seems similar to yours, you can set a custom request code when starting the crop activity.
So you can start the activity with 2 different request codes and check which one has been used on onActivityResult
private static final RC_CROP = 100;
private static final RC_CROP1 = 200;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) // resultCode: -1
{
if (requestCode == CAMERA_REQUEST_CODE) // requestCode: 288
{
Uri picUri = pictureUri;
startCropImageActivity(picUri, RC_CROP);
Toast.makeText(MainActivity.this, "Image 1 save",
Toast.LENGTH_SHORT).show();
}
if (requestCode == CAMERA_REQUEST_CODE1) {
Uri picUri = pictureUri;
startCropImageActivity(picUri, RC_CROP1);
Toast.makeText(MainActivity.this, "Image 2 save",
Toast.LENGTH_SHORT).show();
}
if (requestCode == RC_CROP) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
//put image on first ImageView
}
if (requestCode == RC_CROP1) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
//put image on second ImageView
}
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
// if there is any error show it
Exception error = result.getError();
Toast.makeText(this, "" + error, Toast.LENGTH_LONG).show();
}
}
private void startCropImageActivity(Uri imageUri, int requestCode) {
Intent vCropIntent = CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setMultiTouchEnabled(true)
.getIntent(this);
startActivityForResult(vCropIntent, requestCode)
}
I suggest also to use a switch statement when checking the requestCode

Related

CropActivity doesn't open after picking image

I tired to do same as in https://www.simplifiedcoding.net/crop-image-android-tutorial/. Pick image from gallary and after crop it. But when i'm included it to my fragment it's open gallary but after doesn't show crop activity. But when i did the same directly in activity its work!
My fragment onViewCreated
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SetupUI(view);
SetupProfile();
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
FragmentAdapterProfile adapter = new FragmentAdapterProfile(getActivity(), getActivity().getSupportFragmentManager());
// Set the adapter onto the view pager
pager.setAdapter(adapter);
// Give the TabLayout the ViewPager
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.profileTabs);
tabLayout.setupWithViewPager(pager);
tabLayout.getTabAt(0).setText("About");
tabLayout.getTabAt(1).setText("Setting");
tabLayout.getTabAt(2).setText("Post");
changeavatar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onSelectImageClick(v);
}
});
}
The picking
public void onSelectImageClick(View view) {
CropImage.startPickImageActivity((Activity) context);
}
#Override
public 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(context, data);
// For API >= 23 we need to check specifically that we have permissions to read external storage.
if (CropImage.isReadExternalStoragePermissionsRequired(context, imageUri)) {
// request permissions and handle the result in onRequestPermissionsResult()
mCropImageUri = imageUri;
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
} else {
// no permissions required or already grunted, can start crop image activity
startCropImageActivity(imageUri);
}
}
// handle result of CropImageActivity
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
avatar.setImageURI(result.getUri());
Toast.makeText(context, "Cropping successful, Sample: " + result.getSampleSize(), Toast.LENGTH_LONG).show();
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Toast.makeText(context, "Cropping failed: " + result.getError(), Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (mCropImageUri != null && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// required permissions granted, start crop image activity
startCropImageActivity(mCropImageUri);
} else {
Toast.makeText(context, "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)
.setAspectRatio(1,1)
.start((Activity) context);
}
So i sloved this problem do the next.
I just created secondary Activity (empty) and call crop function in activity after it's work. Problem was in Contexts and Actvities.

How to pass image gotten from camera or gallery to another activity

1. User selects a button to either upload from gallery or capture from camera
From gallery
choose_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
// Sets the type as image/*. This ensures only components of type image are selected
intent.setType("image/*");
//We pass an extra array with the accepted mime types. This will ensure only components with these MIME types as targeted.
String[] mimeTypes = {"image/jpeg", "image/png"};
intent.putExtra(Intent.EXTRA_MIME_TYPES,mimeTypes);
// Launching the Intent
startActivityForResult(intent,1);
}
});
From camera
capture_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(UploadActivity2.this, BuildConfig.APPLICATION_ID + ".provider", createImageFile()));
startActivityForResult(intent, 0);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
2. User selects a photo from gallery or capture from camera and the image is displayed in the current activity
public void onActivityResult(int requestCode,int resultCode,Intent data){
............//grant permission codes here
//If it is from gallery
if (requestCode == 1 && 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 imgDecodableString = cursor.getString(columnIndex);
cursor.close();
//Display image with glide
Glide.with(this).asBitmap().load(imgDecodableString).into(new CustomTarget<Bitmap>() {
#Override
public void onResourceReady(#NonNull Bitmap resource, #Nullable Transition<?
super Bitmap> transition) {
display_image.setImageBitmap(resource);
display_image.setVisibility(View.VISIBLE);
}
}
//If request is from camera
if (resultCode == Activity.RESULT_OK)
switch (requestCode){
case 0:
//Display image in current activity
Glide.with(this)
.load(cameraFilePath)
.into(display_image);
/*display_image.setImageURI(Uri.parse(cameraFilePath));*/
display_image.setVisibility(View.VISIBLE);
break;
}
}
3. I have a 'NEXT' button and when clicked I want to transfer the image displayed (Gotten from either the Gallery or Camera) to another activity, I havn't written a code for passing the image yet
next_upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(UploadActivity2.this, UploadActivity3.class);
startActivity(intent);
}
});
4. I want to know the best way to do this without affecting image quality and memory because in the next activity (UploadAcitivity3), I will be uploading the image passed to the server and saving in a directory
Please follow the steps to achieve this:
Option - 1: If you want to pass multiple images then use below:
Step - 1: Store the selected images path in an ArrayList like below:
private ArrayList<String> selectedImages = new ArrayList<>();
public void onActivityResult(int requestCode,int resultCode,Intent data) {
............//grant permission codes here
//If it is from gallery
if (requestCode == 1 && resultCode == RESULT_OK && null != data) {
....
String imgDecodableString = cursor.getString(columnIndex);
selectedImages.add(imgDecodableString);
}
//If request is from camera
if (resultCode == Activity.RESULT_OK) {
selectedImages.add(cameraFilePath);
}
}
Step - 2: From onClick set the selected images list as extras to intent
next_upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(UploadActivity2.this, UploadActivity3.class);
intent.putStringArrayListExtra("SELECTED_IMAGES", selectedImages);
startActivity(intent);
}
});
Step - 3: Retrieve the selected images from intent in UploadActivity3 like below:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
....
ArrayList<String> selectedImages = getIntent().getStringArrayListExtra("SELECTED_IMAGES");
}
Option - 2: If you want to pass single image then use below:
Step - 1: Store the selected image path like below:
private String selectedImage;
public void onActivityResult(int requestCode,int resultCode,Intent data) {
............//grant permission codes here
//If it is from gallery
if (requestCode == 1 && resultCode == RESULT_OK && null != data) {
....
String imgDecodableString = cursor.getString(columnIndex);
selectedImage = imgDecodableString;
}
//If request is from camera
if (resultCode == Activity.RESULT_OK) {
selectedImage = cameraFilePath;
}
}
Step - 2: From onClick set the selected images list as extras to intent
next_upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(UploadActivity2.this, UploadActivity3.class);
intent.putExtra("SELECTED_IMAGE", selectedImage);
startActivity(intent);
}
});
Step - 3: Retrieve the selected images from intent in UploadActivity3 like below:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
....
String selectedImage = getIntent().getStringExtra("SELECTED_IMAGE");
Glide.with(this).load(selectedImage).into(image_view);
}
You can send the image path through Intent
next_upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(UploadActivity2.this, UploadActivity3.class);
intent.putExtra("path", imagePath);
startActivity(intent);
}
});
You already have image path for capturing image is cameraFilePath
and for gallery image imgDecodableString.
Declare String imagePath; as class variable and assign them in onActivityResult.
imagePath = imgDecodableString;//For Gallery
imagePath = cameraFilePath;//For Capture image
Receive path in UploadActivity3.class
String imagePath = getIntent().getStringExtra("path");
Use this path in second activity as you want.

Capture photo intent resultCode

How can I detect wether the user take picture and selects it (with the confirm button on camera) or they just turn on a camera, take a picture and remove it (with the cancel button on camera)
When the user take picture I am loading that picture into an ImageView. If user hits confirm button then everything is OK but if user don't want that picture and decide to hit cancel button then the ImageView goes blank.
This is my camera intent :
void capturePhoto() {
// ImagePicker.pickImage(this, "Select your image:");
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 f = null;
try {
f = setUpPhotoFile();
mCurrentPhotoPath = f.getAbsolutePath();
Uri photoURI = Uri.fromFile(f);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
} catch (IOException e) {
e.printStackTrace();
f = null;
mCurrentPhotoPath = null;
pictureUri = null;
}
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
And onActivityResult, in both cases the resultCode is always 1. (note that RESULT_OK is -1) and I dont know why.
This is how I set image to ImageView using Glide:
Glide.with(this).load(mCurrentPhotoPath).centerCrop().into(imageView);
Any Suggestions?
Thanks!
you just need to pass if statement in onActivityresult
cause if you use directly that URI or whatever you use which has no any frame set cause user cancel it so just do as given
//if needed than
//public static final int RESULT_OK = -1;
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case REQUEST_TAKE_PHOTO:
//do your stuff here
}
}
You can use below code
static final int REQUEST_IMAGE_CAPTURE = 1;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
if (isCameraPermissionEnabled()) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA},
1);
}
}
}
public boolean isCameraPermissionEnabled() {
return !(Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED );
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
mBitmap = (Bitmap) extras.get("data");
imageView.setBackground(new BitmapDrawable(getResources(),mBitmap));
}
}
//For more information https://developer.android.com/training/camera/photobasics.html

Error with image view when displaying an image by camera capturing

i am new to android and i am trying to make my phone cam take a picture and display it in an image view. When the image is captured, it is saved correctly but after that the app stops working when the image should be displayed in an image view. Any help is appreciated. I searched some topics but still nothing works.
Here is the code:
package myfirstapp.myapps.me.camera;
import ...
public class MainActivity extends ActionBarActivity {
ImageButton camBtn;
ImageView imageView;
ScrollView scrollView;
private File imageFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void OpenCam(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
imageFile=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"image.jpg");
Uri tempURI=Uri.fromFile(imageFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, tempURI);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0)//==0 the same where startActivityForResult(intent, 0) so we are in the same process
{
switch (resultCode){
case Activity.RESULT_OK:
if(imageFile.exists())
{
Toast.makeText(MainActivity.this, "Image was saved at "+imageFile.getAbsolutePath(), Toast.LENGTH_SHORT)
.show();
Bitmap myBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageView);
myImage.setImageBitmap(myBitmap);
}
else
{
Toast.makeText(MainActivity.this, "Image wasn't saved", Toast.LENGTH_SHORT)
.show();
}
break;
case Activity.RESULT_CANCELED:
Toast.makeText(MainActivity.this, "Image capture was cancelled", Toast.LENGTH_SHORT)
.show();
break;
}
}
}
}
Stacktrace
Caused by: java.lang.RuntimeException: Failure delivering result
ResultInfo{who=null, request=0, result=-1, data=null} to activity
{myfirstapp.myapps.me.camera/myfirstapp.myapps.me.camera.MainActivity}:
java.lang.NullPointerException at
android.app.ActivityThread.deliverResults(ActivityThread.java:3410) at
android.app.ActivityThread.performResumeActivity(ActivityThread.java:2817)
at
android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2859)
Please go through this Code:
public static final int REQUEST_IMAGE_CAPTURE = 1;
public static final int RESULT_LOAD_IMAGE = 10;
private Bitmap myBitmap;
ImageView myImage ;
public void OpenCam(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null)
{
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
And also,
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK)
{
Bundle extras = data.getExtras();
myBitmap= (Bitmap) extras.get("data");
myImage = (ImageView) findViewById(R.id.imageView);
myImage.setImageBitmap(myBitmap);
}
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();
myBitmap= BitmapFactory.decodeFile(picturePath);
// photoUri = picturePath;
myImage.setImageBitmap(myBitmap);
}
}
Why are you first saving and trying to show the saved image file. Use the returned data from onActivityResult. Before file is actually created in the memory, broadcast is sent so it can refresh the directory and show the new file. But better is to use what camera intent is returning as data.
Replace your this code
Bitmap myBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageView);
myImage.setImageBitmap(myBitmap);
with this
ImageView myImage = (ImageView) findViewById(R.id.imageView);
Bitmap photo = (Bitmap) data.getExtras().get("data");
myImage.setImageBitmap(photo);
first : comment the line
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); // no need to write for capture camera
second : use this line
imageFile=new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/abc); // abc folder name
instead of
imageFile=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"image.jpg");
Note : your code work upto kitkat but lollipop it will crash because in lollipop imageFile return null so Uri failed to convert in file . Hope your problem will resolve . and one more thing before open camera u should check that sdcard permission .

android : how to add image from gallery and delete image with a Button

i want to load image that taken from galllery and camera, when user click on capture button, image will be capture from camera phone device, when user click on add_gallery button, image will be taken from gallery, my problem is when i choose an image from gallery, it is not display on my activity (on My ImageView named by foto_dp).
this is my code :
#Override
public void onClick(View arg0) {
switch (arg0.getId()){
break;
case R.id.capture_dp:
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
startActivityForResult(intent, TAKE_PHOTO_CODE);
break;
case R.id.add_galery_dp:
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
i.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
startActivityForResult(i, PICK_FROM_GALLERY);
break;
case R.id.delete_image_dp:
break;
}
public Uri setImageUri() {
// Store image in dcim
File file = new File(Environment.getExternalStorageDirectory() +"/android/data/spaj_foto/spaj_foto("+counter+").png");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
}
public String getImagePath() {
return imgPath;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_CANCELED) {
if (requestCode == TAKE_PHOTO_CODE) {
selectedImagePath = getImagePath();
foto_dp.setImageBitmap(decodeFile(selectedImagePath));
if (requestCode == PICK_FROM_GALLERY) {
selectedImagePath = getImagePath();
foto_dp.setImageBitmap(decodeFile(selectedImagePath));
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
public Bitmap decodeFile(String path) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 70;
// Find the correct scale value. It should be the power of 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeFile(path, o2);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
is there anywrong with my code? and how to delete image with a button on my activity? i hope someone can help me to solve my problem, thank you
You do not need to decode file. Try following code
private final int REQUEST_CODE_CAMERA_IMAGE = 1000;
private final int REQUEST_CODE_EXTERNAL_IMAGE = 2000;
//select picture from external storage
btnChoosePicture.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// choose picture from gallery
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,
REQUEST_CODE_EXTERNAL_IMAGE);
}
});
//take picture from camera
btnTakePhoto.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// start camera to take picture
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT,
setImageUri());
startActivityForResult(intent,
REQUEST_CODE_CAMERA_IMAGE);
}
});
Display image like this
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
// get image from camera
case REQUEST_CODE_CAMERA_IMAGE:
if (resultCode == Activity.RESULT_OK) {
imageView.setImageUri(setImageUri());
}
break;
// get image from external storage
case REQUEST_CODE_EXTERNAL_IMAGE:
if (resultCode == Activity.RESULT_OK) {
imageView.setImageUri(data.getData());
}
break;
default:
break;
}
}
To delete image
btnDelete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
File file = new File(imagePath);
if(file.exist())
file.delete();
}
});
When you get image url from gallery, just delete it like file
button.setOnClickListener(deleteListener);
OnClickListener deleteListener = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
File file = new File(imagePath);
file.delete();
}
};
Show image use imageview

Categories