Getting the file path from a picture in ImageView - android

Alright I am making an Android app, and using the CAPTURE_PIC_REQUEST to take a picture and store it as a preview on the screen in an imageviewer. I wanted to know how to get the Uri and actually path because I am planning on taking that information, saving it and accessing it later. So I can't figure how to get the Uri or path name from that picture I just took. Here is the code from my activity that is handling
package com.CS480;
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class AddEx extends Activity {
static final int CAMERA_PIC_REQUEST = 1337;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.add);
Button camera = (Button) findViewById(R.id.picButton);
camera.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PIC_REQUEST) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ImageView image = (ImageView) findViewById(R.id.returnedPic);
image.setImageBitmap(thumbnail);
}
}
}
So how from that image that I am getting back on the app do I get the file location

As far as I know, you can do something like this:
private Uri mImageCaptureUri;
public class AddEx extends Activity {
static final int CAMERA_PIC_REQUEST = 1337;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.add);
Button camera = (Button) findViewById(R.id.picButton);
camera.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent cameraIntent =
new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
mImageCaptureUri);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PIC_REQUEST) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ImageView image = (ImageView) findViewById(R.id.returnedPic);
image.setImageBitmap(thumbnail);
String pathToImage = mImageCaptureUri.getPath();
// pathToImage is a path you need.
// If image file is not in there,
// you can save it yourself manually with this code:
File file = new File(mImageCaptureUri.getPath());
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut); // You can choose any format you want
}
}
From Android documentation about android.provider.MediaStore.EXTRA_OUTPUT:
The name of the Intent-extra used to indicate a content resolver Uri
to be used to store the requested image or video.

You can try getting the URI of the image with
data.getExtras.get("URI");
but this might not work. What you can do is simply save the Bitmap yourself. See this question for a guide on how to do that: Save bitmap to location

When you take your image, you must store it somewhere to get the location of the image.
To do this, you can store to the MediaStore:
String result = MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "", "");
imageFileUri = Uri.parse(result);

Try this get image file path form Bitmap
public void uploadBitmap(Context mContext, Bitmap bitmap) {
String imagePath = null;
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
Uri uri;
Cursor cursor = mContext.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.Media.DATA, MediaStore.Images.Media.DATE_ADDED, MediaStore.Images.ImageColumns.ORIENTATION}, MediaStore.Images.Media.DATE_ADDED, null, "date_added DESC");
if (cursor != null && cursor.moveToFirst()) {
do {
uri = Uri.parse(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)));
imagePath = uri.toString();
Log.d("pathatka", uri.toString());
break;
} while (cursor.moveToNext());
cursor.close();
}
}

The android documentation has an example of defining a file URI for saving the output when you setup the Intent for your image capture.

Related

custom gallery cropping window in android

After struggling with Camera intents for too long, I have now finally created a custom camera experience for my app by using SurfaceView and the Camera api. It’s pretty awesome as I now have complete control over the picture taking experience. I would like to take control over the gallery experience as well. It’s not clear how I might do that? Any advice? Basically I am hoping for the following user experience
click on gallery button to view photos in your gallery
select a photo from the gallery
the selected photo shows up in a customized preview in which the user can move the photo around to select which portion to use. Notice that this is a sort of cropping that happens within a fixed area (in my case a square the size of the phone's width): no resizing allowed; the area of the picture within the window is the area used. Pretty much most of the social media apps out there do it that way. I just don’t have a clue how they manage that preview/edit-window.
What I know so far:
I can still use the gallery intent to let the user select the image
The part where I am stuck is on how to create the custom edit experience that lets the user choose an area of the image to show (fixed size square). Again, this is not resize-cropping; but rather the user can move the image around to choose which sub-area fits the window.
Thanks for any advice
Ok Here We Go!
Activity To Select The Image From Gallery.
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
public class GalleryUtil extends Activity{
private final static int RESULT_SELECT_IMAGE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
private static final String TAG = "GalleryUtil";
String mCurrentPhotoPath;
File photoFile = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
//Pick Image From Gallery
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_SELECT_IMAGE);
}catch(Exception e){
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
case RESULT_SELECT_IMAGE:
if (resultCode == Activity.RESULT_OK && data != null && data.getData() != null) {
try{
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();
//return Image Path to the Main Activity
Intent returnFromGalleryIntent = new Intent();
returnFromGalleryIntent.putExtra("picturePath",picturePath);
setResult(RESULT_OK,returnFromGalleryIntent);
finish();
}catch(Exception e){
e.printStackTrace();
Intent returnFromGalleryIntent = new Intent();
setResult(RESULT_CANCELED, returnFromGalleryIntent);
finish();
}
}else{
Log.i(TAG,"RESULT_CANCELED");
Intent returnFromGalleryIntent = new Intent();
setResult(RESULT_CANCELED, returnFromGalleryIntent);
finish();
}
break;
}
}
}
Activity To Crop The Selected Image:
public class ImageSelecter extends Activity{
private final int GALLERY_ACTIVITY_CODE=200;
private final int RESULT_CROP = 400;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
btn_choose.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Start Activity To Select Image From Gallery
Intent gallery_Intent = new Intent(getApplicationContext(), GalleryUtil.class);
startActivityForResult(gallery_Intent, GALLERY_ACTIVITY_CODE);
break;
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_ACTIVITY_CODE) {
if(resultCode == Activity.RESULT_OK){
picturePath = data.getStringExtra("picturePath");
//perform Crop on the Image Selected from Gallery
performCrop(picturePath);
}
}
if (requestCode == RESULT_CROP ) {
if(resultCode == Activity.RESULT_OK){
Bundle extras = data.getExtras();
Bitmap selectedBitmap = extras.getParcelable("data");
// Set The Bitmap Data To ImageView
image_capture1.setImageBitmap(selectedBitmap);
image_capture1.setScaleType(ScaleType.FIT_XY);
}
}
}
private void performCrop(String picUri) {
try {
//Start Crop Activity
Intent cropIntent = new Intent("com.android.camera.action.CROP");
// indicate image type and Uri
File f = new File(picUri);
Uri contentUri = Uri.fromFile(f);
cropIntent.setDataAndType(contentUri, "image/*");
// set crop properties
cropIntent.putExtra("crop", "true");
// indicate aspect of desired crop
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
// indicate output X and Y
cropIntent.putExtra("outputX", 280);
cropIntent.putExtra("outputY", 280);
// retrieve data on return
cropIntent.putExtra("return-data", true);
// start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, RESULT_CROP);
}
// respond to users whose devices do not support the crop action
catch (ActivityNotFoundException anfe) {
// display an error message
String errorMessage = "your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
This all hope this will give you a head up:)

Image not setting in ImageView after taking picture from Camera

I've have develop my own camera app for mandatory configuration, when i try to show the captured image in next activity which displays whether to save it or not?
I'm not able to fetch the image which i captured and displays on my ImageView. I'm absolutely getting absPathUri with proper path.
Code snippets:-
imgView = (ImageView)findViewById(R.id.picView);
Bundle b= getIntent().getExtras();
absPathUri = Uri.parse(b.getString("URI"));
Toast.makeText(getApplicationContext(), ""+absPathUri, Toast.LENGTH_SHORT).show();
if(absPathUri!=null)
{
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE));
imgView.setImageURI(absPathUri);
}
On Further dive in the reason why I'm unable to set the ImageView, throws the Null Pointer Exception which is due to File Not Found. If applicatoin is in debug mode it displays the proper Image on ImageView. It seems that mediaStore get Refreshed till the debugging hits.
File imgFile = new File(getPath(absPathUri));
Toast.makeText(getApplicationContext(), "ImageFile Exists"+imgFile.exists(), Toast.LENGTH_SHORT).show();
if(imgFile.exists())
{
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
imgView.setImageBitmap(myBitmap);
}
public String getPath(Uri photoUri) {
String filePath = "";
if (photoUri != null) {
String[] filePathColumn = { MediaStore.Images.Media.DATA };
try
{
Cursor cursor = getContentResolver().query(photoUri,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
cursor.close();
}catch(Exception e)
{
Toast.makeText(getApplicationContext(), ""+e, Toast.LENGTH_SHORT).show();
}
}
return filePath;
}
Tried Solution:-
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE));
Can anybody guide me where I'm getting wrong in displaying Image on ImageView?
As suggested by gnuanu, setImageURI() is not better to use as reading and decoding on the UI thread, which can cause a latency hiccup.
Better to use the following:-
setImageDrawable(android.graphics.drawable.Drawable) or setImageBitmap(android.graphics.Bitmap) and BitmapFactory instead.
Still these methods didn't solve my problem. As I was taking Picture with Camera and onClick of it sending to Next Activity which may cause latency hiccups.
So better to pass to another activity after some peroid of time . . just a sec is totally convient to get through it.
Snippet which solve my issue:-
final Intent picIntent = new Intent(CameraActivity.this,PicSaveActivity.class);
picIntent.putExtra("URI", pathUri.toString());
Handler handler = new Handler()
{
public void handleMessage(Message msg) {
startActivityForResult(picIntent, PICTAKEN);
};
};
Message msg = handler.obtainMessage();
handler.sendMessageDelayed(msg, 1000);
In Next Activity, catch the URI and rotate the Image as it would be in landscape mode.
if(absPathUri!=null)
{
Bitmap myImg = BitmapFactory.decodeFile(absPathUri.getPath());
Matrix matrix = new Matrix();
matrix.postRotate(90);
Bitmap rotated = Bitmap.createBitmap(myImg, 0, 0, myImg.getWidth(), myImg.getHeight(),
matrix, true);
imgView.setImageBitmap(rotated);
}
I don't really know what's wrong in your code, and my answer uses a completely different approach to taking a photo with the camera and displaying it in an ImageView, but it's a working solution that might help you.
In your first Activity (call it CameraActivity), you can do the following:
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class CameraActivity extends PortraitActivity {
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
private Bitmap photo;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
}
/** Method to open camera and take photo */
public void takePhoto(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
/** Method called after taking photo and coming back to current Activity */
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST) {
photo = (Bitmap) data.getExtras().get("data");
Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("BitmapImage", photo);
startActivity(intent);
}
}
}
In the second activity (call it NewActivity), just put the following code in the onCreate method, after having assigned imageView to the corresponding view in the XML layout.
Intent intent = getIntent();
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");
imageView.setImageBitmap(photo);
The reference clearly states: The path to the file is contained in the Intent.mData field.
Therefore, you need
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, absPathUri));
You probably also need to let the broadcast complete before you get the results; using
imgView.post(new Runnable() { public void run() { imgView.setImageURI(absPathUri); } }
should suffice.

Capturing a picture and than displaying within an ImageView - Android

Hey guys I am using my webcam to simulate a camera in the emulator and when I go to take the picture and select the check mark button to use the picture I run across an error while trying to display the image back into my ImageView on the app.
Here is my code:
Initiator:
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, CAMERA_PIC_REQUEST);
function....
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST) {
if (resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
//OI FILE Manager
filemanagerstring = selectedImageUri.getPath();
//MEDIA GALLERY
selectedImagePath = getPath(selectedImageUri);
img.setImageURI(selectedImageUri);
imagePath.getBytes();
Bitmap bm = BitmapFactory.decodeFile(imagePath);
Log.w("Here","error");
Bitmap bm = BitmapFactory.decodeFile(imagePath);
ImageView image = (ImageView) findViewById(R.id.gimg1);
image.setImageBitmap(bm);
} else if (resultCode == RESULT_CANCELED){
}
}
}
I run across a runtime error
Suggestions and thoughts are needed!
You can use the following codes. It's fully functional and allows you set image from both your camera and gallery as well. I am almost sure that your runtime error is "OutOfMemoryError: bitmap size exceeds VM budget" as I am seeing that you have loaded the captured image directly to your imageView. You should scale it , please take a look at the method called GetScaledBitmap in my following code. Hope your codes will work ok if you use that method only when you load the image to your imageview. Full example is done for you , Hope it helps.
package com.tseg.android.mctemplate;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.tseg.android.mctemplate.R;
public class PhotoTake extends Activity {
Button add1 ;
ImageView img1 ;
private static final int ACTIVITY_PHOTOS = 0;
private static final String PACKAGE = "spine";
Uri mCapturedImageURI;
private int photo_count = 0;
boolean hasPhotos = false;
Bitmap bitmap;
String[] paths;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.photo);
add1 = (Button) findViewById(R.id.add1);
img1 = (ImageView) findViewById(R.id.img1);
add1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
ShowDialog(100, 1000);
}
});
}
void ShowDialog(final int req, final int choose) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("");
builder.setTitle("Select Photo")
.setCancelable(false)
.setNegativeButton("Take Photo",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
File pictureFileDir = getDir();
if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {
Log.d("Photo Take", "Can't create directory to save image.");
Toast.makeText(PhotoTake.this , "Can't create directory to save image.",
Toast.LENGTH_LONG).show();
return;
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
String date = dateFormat.format(new Date());
String photoFile = "Picture_" + date + ".jpg";
String filepath = pictureFileDir.getPath() + File.separator;
File imageFile = new File(filepath , photoFile);
ContentValues image = new ContentValues();
image.put(Images.Media.TITLE, photoFile);
image.put(Images.Media.DISPLAY_NAME, photoFile);
image.put(Images.Media.DESCRIPTION, "Accident data Accachment " + date);
image.put(Images.Media.DATE_ADDED, date);
image.put(Images.Media.DATE_TAKEN, date);
image.put(Images.Media.DATE_MODIFIED, date);
image.put(Images.Media.MIME_TYPE, "image/jpeg");
image.put(Images.Media.ORIENTATION, 0);
File parent = imageFile.getParentFile();
String path = parent.toString().toLowerCase();
String name = parent.getName().toLowerCase();
image.put(Images.ImageColumns.BUCKET_ID, path.hashCode());
image.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, name);
image.put(Images.Media.SIZE, imageFile.length());
image.put(Images.Media.DATA, imageFile.getAbsolutePath());
mCapturedImageURI = PhotoTake.this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, image);
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
mCapturedImageURI);
startActivityForResult(intent, req);
}
})
.setPositiveButton("Choose Existing",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(
intent, "Complete action using"),
choose);
}
});
AlertDialog alert = builder.create();
alert.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// From camera
if (requestCode == 100 && resultCode == Activity.RESULT_OK) {
if (mCapturedImageURI != null) {
img1.setImageBitmap(getScaledBitmap(mCapturedImageURI));;
System.out.println("Onactivity Result uri = " + mCapturedImageURI.toString());
} else {
Toast.makeText(PhotoTake.this, "Error getting Image",
Toast.LENGTH_SHORT).show();
}
}
//From gallery
if (requestCode == 1000) {
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = data.getData();
System.out.println("Content Path : " + selectedImage.toString());
if (selectedImage != null) {
img1.setImageBitmap(getScaledBitmap(selectedImage));
} else {
Toast.makeText(PhotoTake.this, "Error getting Image",
Toast.LENGTH_SHORT).show();
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(PhotoTake.this, "No Photo Selected",
Toast.LENGTH_SHORT).show();
}
}
}
public Bitmap getBitmap(String path) {
Bitmap myBitmap = null;
File imgFile = new File(path);
if (imgFile.exists()) {
myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
}
return myBitmap;
}
public String getPath(Uri photoUri) {
String filePath = "";
if (photoUri != null) {
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(photoUri,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
cursor.close();
}
return filePath;
}
private File getDir() {
File sdDir = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return new File(sdDir, "SpineAttachments");
}
private Bitmap getScaledBitmap(Uri uri){
Bitmap thumb = null ;
try {
ContentResolver cr = getContentResolver();
InputStream in = cr.openInputStream(uri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize=8;
thumb = BitmapFactory.decodeStream(in,null,options);
} catch (FileNotFoundException e) {
Toast.makeText(PhotoTake.this , "File not found" , Toast.LENGTH_SHORT).show();
}
return thumb ;
}
}
if(requestCode==CAMERA_PIC_REQUEST && resultCode==RESULT_OK){
Bitmap image = (Bitmap) data.getExtras().get("data");
ImageView image = (ImageView) findViewById(R.id.gimg1);
image.setImageBitmap(image);
}
if(requestCode==CAMERA_PIC_REQUEST && resultCode==RESULT_OK){
Bitmap image = (Bitmap) data.getExtra("data");
image_taken.setImageBitmap(image);
}
You were calling data.getData() whereas it should have been data.getExtra("data") as data is an intent which you will have put the bitmap
Very Simple way to Click button and set store image in imageview.
`public class MainActivity extends Activity {
private static final int CAMERA_PIC_REQUEST = 22;
Uri cameraUri;
Button BtnSelectImage;
private ImageView ImgPhoto;
private String Camerapath ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImgPhoto = (ImageView) findViewById(R.id.imageView1);
BtnSelectImage = (Button) findViewById(R.id.button1);
BtnSelectImage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
try {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Couldn't load photo", Toast.LENGTH_LONG).show();
}
}
});
}
#Override
public void onActivityResult(final int requestCode, int resultCode, Intent data) {
try {
switch (requestCode) {
case CAMERA_PIC_REQUEST:
if (resultCode == RESULT_OK) {
try {
Bitmap photo = (Bitmap) data.getExtras().get("data");
ImgPhoto.setImageBitmap(photo);
} catch (Exception e) {
Toast.makeText(this, "Couldn't load photo", Toast.LENGTH_LONG).show();
}
}
break;
default:
break;
}
} catch (Exception e) {
}
}
}`
Set this Manifest.
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" android:required="false"></uses-feature>

open camera using intent

I want to use intent to open camera in Android .
I used the following code but when i press the button (whose action is onclick() function the app closes on itself .
public void onclick(int actionCode){
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, actionCode);
}
public static boolean isIntentAvailable(Context context, String action) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action);
List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
If someone can help me .
File destination;
Uri selectedImage;
public static String selectedPath1 = "NONE";
private static final int PICK_Camera_IMAGE = 2;
private static final int SELECT_FILE1 = 1;
public static Bitmap bmpScale;
public static String imagePath;
mcamera = (Button) findViewById(R.id.button1);
mcamera.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String name = dateToString(new Date(), "yyyy-MM-dd-hh-mm-ss");
destination = new File(Environment
.getExternalStorageDirectory(), name + ".jpg");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(destination));
startActivityForResult(intent, PICK_Camera_IMAGE);
}
});
// ......................gallery_function..........//
mgallery = (Button) findViewById(R.id.button2);
mgallery.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
openGallery(SELECT_FILE1);
}
});
for intent
// .........................Gallery function.................//
public void openGallery(int SELECT_FILE1) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select file to upload "),
SELECT_FILE1);
}
//............ intent .........
// ..................
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
Uri selectedImageUri = null;
String filePath = null;
switch (requestCode) {
case SELECT_FILE1:
if (resultCode == Activity.RESULT_OK) {
selectedImage = imageReturnedIntent.getData();
if (requestCode == SELECT_FILE1) {
selectedPath1 = getPath(selectedImage);
// mimagepath.setText(selectedPath1);
// Toast.makeText(Camera.this, "" + selectedPath1 + "",
// 500).show();
if (selectedPath1 != null) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
// image path `String` where your image is located
BitmapFactory.decodeFile(selectedPath1, options);
// Log.d("setpath ", "setpath " + selectedPath1);
;
}
}
break;
case PICK_Camera_IMAGE:
if (resultCode == RESULT_OK) {
try {
in = new FileInputStream(destination);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
imagePath = destination.getAbsolutePath();
// Toast.makeText(Camera.this, "" + imagePath +
// "",Toast.LENGTH_LONG).show();
break;
}
}
try this code
public static final int CAMERA_PIC_REQUEST = 1;//firstly define this
Intent photo= new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(photo, CAMERA_PIC_REQUEST);
The parameter passed to an "on-click" method is of type View not int as you show.
According to this tutorial your onClick method should be as follows:
public void onclick( View v ){
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, CAMERA_PIC_REQUEST);
}
Where CAMERA_PIC_REQUEST is defined as (although I'm not quite sure why you would need to statically hard-code this value in your application):
private static final int CAMERA_PIC_REQUEST = 1337;
Update
CAMERA_PIC_REQUEST is used to uniquely identify the result being returned to onActivityResult. Multiple startActivityForResultrequests could be outstanding at one time.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST) {
if (resultCode == RESULT_OK) {
tv.setText("Got picture!");
imageData = (Bitmap) data.getExtras().get("data");
ImageView image = (ImageView) findViewById(R.id.imageView1);
image.setImageBitmap(imageData);
} else if (resultCode == RESULT_CANCELED){
tv.setText("Cancelled");
}
}
}
please have a look at this code, this is working fine with me
//define the file-name to save photo taken by Camera activity
fileName = "new-photo-name.jpg";
//create parameters for Intent with filename
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION,"Image capture by camera");
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
also apply this method to read image when you taken the image from camera.
//handling intent responses
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK)
try {
if (bitmap != null) {bitmap.recycle();}
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(imageUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
imageUriString = cursor.getString(column_index);
getContentResolver().notifyChange(imageUri, null);
ContentResolver cr = getContentResolver();
try {
bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, imageUri);
imageButtonPictureShop.setImageBitmap(bitmap);
// this.uploadImage();
this.executeMultipartPost();
// this.uploadFile(imageUriString);
}
catch (Exception e)
{
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT).show();
if(e.getMessage() != null)Log.e("Exception" , e.getMessage());
else Log.e("Exception" , "Exception");
e.printStackTrace();
}
}
catch (Exception e)
{
if(e.getMessage() != null)Log.e("Exception" , e.getMessage());
else Log.e("Exception" , "Exception");
e.printStackTrace();
}
super.onActivityResult(requestCode, resultCode, data);
}
I know this question old and answered, but for those who are asking how to get the image file ?
heres the solution.
String ExternalStorageDirectoryPath = Environment.getExternalStorageDirectory().getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + "/DCIM/Camera";
File targetDirector = new File(targetPath);
File[] files = targetDirector.listFiles()
String ImagePath = files[ file.files-1 ].getAbsolutePath();
Bitmap bmp = BitmapFactory.decodeFile(pathName);
ivImage.setImageBitmap( bmp );
Also you don't need to add Camera permissions on your Manifest file.
-Cheers and vote up if this help you
-Happy Codings..
It's very easy to start camera from your Android app:
just write two lines code in onClick method
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_PIC_REQUEST );
Add one constant field in your class (you can use any random number instead of 7)
private int CAMERA_PIC_REQUEST = 7;
After a lot of research I found this solution. Just to make things clear I created an entire app for this question which serves the purpose of opening the camera clicking a photo and setting the image as the ImageBitmap of an ImageView. The code asked in this question starts at the second block i.e. the setView() method which is below the onCreate() method following which we have the onActivityResult() method
Here is a demo of the app.
Below I have Attached the MainActivity.java file
package com.cr7.opencamera;
import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private Button buttonCaptureImageFromCamera;
private Uri imageUri;
private ImageView imageViewCameraImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Button that will open the camera
buttonCaptureImageFromCamera = findViewById(R.id.buttonCaptureImageFromCamera);
// ImageView that will store the image
imageViewCameraImage = findViewById(R.id.imageViewCameraImage);
askPermission();
}
Here imageUri is a global variable so that it can be used in the onActivityResult() method
// Sets OnClickListener for the button if storage permission is given
private void setView() {
buttonCaptureImageFromCamera.setOnClickListener(v -> {
String fileName = "new-photo-name.jpg";
// Create parameters for Intent with filename
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION, "Image capture by camera");
imageUri =
getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, 1231);
});
}
This is the onActivityResult method. Here I've used imageUri i.e. the global variable of type Uri which was initialized in the OnClickListener of the button in the setView() method above.
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1231 && resultCode == Activity.RESULT_OK) {
try {
ContentResolver cr = getContentResolver();
try {
// Creating a Bitmap with the image Captured
Bitmap bitmap = MediaStore.Images.Media.getBitmap(cr, imageUri);
// Setting the bitmap as the image of the
imageViewCameraImage.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
} catch (IllegalArgumentException e) {
if (e.getMessage() != null)
Log.e("Exception", e.getMessage());
else
Log.e("Exception", "Exception");
e.printStackTrace();
}
}
}
Remaining code...
// Asking user for storage permission
public void askPermission() {
// Checking if the permissions are not granted.
if (
ContextCompat.checkSelfPermission(
this,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE
) != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(
this,
android.Manifest.permission.READ_EXTERNAL_STORAGE
) != PackageManager.PERMISSION_GRANTED
) {
// If not granted requesting Read and Write storage
ActivityCompat.requestPermissions(this, /*You can ask for multiple request by adding
more permissions to the string*/new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE}, 60);
} else {
// If permissions are granted we proceed by setting an OnClickListener for the button
// which helps the user pick the image
setView();
}
}
// This method is called after the permissions have been asked i.e. the dialog that says
// allow or deny
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// Now by default we assume that the permission has not been granted
boolean allPermissionsGranted = false;
// Now we check if the permission was granted
if ( requestCode == 60 && grantResults.length > 0) {
// If all the permissions are granted allPermissionsGranted is set to true else false
allPermissionsGranted = grantResults[0] == PackageManager.PERMISSION_GRANTED
&&
grantResults[1] == PackageManager.PERMISSION_GRANTED;
}
// If permissions are granted we call the setView Method which prompts the user to pick
// an Image either by the clicking it now or picking from the gallery
if ( allPermissionsGranted ) {
setView();
}
}
}
These blocks of code are in sequence i.e. if you merge all these blocks you get the complete MainActivity.java class.
If you wan to Implement this app you need yo create a layout file with an ImageView with an id "imageViewCameraImage"and a button with an id "buttonCaptureImageFromCamera".
Hope this helps. I know this is long and I'm making it longer by writing this.
Regards,
Joel

Image sd card path from intent gallery

I am starting gallery through intent otherwise its giving problem to display gallery in grid view.
But i want the actual sd card path of the image i am selection from the gallery, opened by intent.
here is the code..
Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/jpg");
photoPickerIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/Pictures/image.jpg"));
startActivityForResult(photoPickerIntent, 1);
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_CANCELED) {
showToast(this,"Activity cancelled");
return;
}
else if(resultCode == RESULT_OK) {
System.out.println("requestCode--"+requestCode);
System.out.println("resultCode--"+resultCode);
System.out.println("data--"+intent.getData());
Uri uri = intent.getData();
String data = uri.getPath();
System.out.println("uri.getPath()--"+uri.getPath());
System.out.println("type--"+intent.getType());
System.out.println("path--"+Environment.getExternalStorageState());
return;
}
switch (requestCode) {
case CAMERA_ACTIVITY:
Bundle b = intent.getExtras();
Bitmap bm = (Bitmap) b.get("data");
// mImageView.setImageBitmap(bm); // Display image in the View
// large image?
if (b.containsKey(MediaStore.EXTRA_OUTPUT)) { // large image?
Log.i(TAG, "This is a large image");
showToast(this,"Large image");
// Should have to do nothing for big images -- should already saved in MediaStore ... but
MediaStore.Images.Media.insertImage(getContentResolver(), bm, null, null);
}
else {
Log.i(TAG, "This is a small image");
showToast(this,"Small image");
MediaStore.Images.Media.insertImage(getContentResolver(), bm, null, null);
}
break;
}
}
}
I am getting all data from intent object. But i want the sd card path for the image what i am selecting to upload that image in server..
how do i get that?
You may want something like this:
Uri uri = (Uri) intent.getExtras().get("android.intent.extra.STREAM");
if ( intent.getAction().equals( Intent.ACTION_SEND ) )
{
if ( uri.getScheme().equals("content"))
{
Cursor cursor = getContentResolver().query( uri, null, null, null, null );
cursor.moveToFirst();
filePath = cursor.getString(cursor.getColumnIndexOrThrow(Images.Media.DATA));
}
}
This Code may help you
This code will pop up one Dialog Box with Camera and gallery and devices SD card to get the images path.
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import com.fanosedu.R;
public class FileAttachPopUpUtils extends Activity {
private View rootView;
private Dialog popup;
private Button Assig_PopUp_DeviceBtn;
private Button Assig_PopUp_GalaryBtn;
private Button Assi_PopUp_CameraBtn;
private Button Assig_PopUp_CancelPopupBtn;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.assignment_popupfile);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
/*
* getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
* WindowManager.LayoutParams.FLAG_FULLSCREEN);
*/
popup = new Dialog(this);
// popup.requestWindowFeature(Window.FEATURE_NO_TITLE);
// popup.getWindow().setBackgroundDrawable(new
// ColorDrawable(android.graphics.Color.TRANSPARENT));
popup.setContentView(R.layout.assignment_popupfile);
popup.setCanceledOnTouchOutside(false);
popup.show();
Assig_PopUp_DeviceBtn = (Button) popup
.findViewById(R.id.Assignment_PopUp_DeviceBtn);
Assig_PopUp_GalaryBtn = (Button) popup
.findViewById(R.id.Assignment_PopUp_GalaryBtn);
Assi_PopUp_CameraBtn = (Button) popup
.findViewById(R.id.Assignment_PopUp_CameraBtn);
Assig_PopUp_CancelPopupBtn = (Button) popup
.findViewById(R.id.Assignment_PopUp_CancelPopupBtn);
Assig_PopUp_DeviceBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/*
* Toast.makeText(FileAttachPopUpUtils.this,
* "Device File In-Progress", Toast.LENGTH_SHORT) .show();
*/
Intent intent = new Intent(FileAttachPopUpUtils.this,
FileExplore.class);
startActivity(intent);
popup.dismiss();
finish();
}
});
Assig_PopUp_GalaryBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
});
Assi_PopUp_CameraBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// ///////////////////////////////////////////////////////////////
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 1);
}
});
Assig_PopUp_CancelPopupBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
popup.dismiss();
FileAttachPopUpUtils.this.finish();
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_OK) {
if (requestCode == 1) {
/*
* Intent intent = new Intent( Intent.ACTION_PICK,
* android.provider
* .MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
* startActivityForResult(intent, 2);
*/
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
// mImage.setImageBitmap(thumbnail);
// 3
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
// 4
String name;
int n = 100000;
int rand;
rand = new Random().nextInt(n);
name = "Image-" + rand + ".jpg";
// File fileimage = new File(path, name);
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + name);
System.out.println("FILE PATH=======>>>>>>>>>>"
+ file.toString());
try {
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
// 5
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Assignments.mulPathArry.add(file.toString());
// Here You will get the full path
FileAttachPopUpUtils.this.finish();
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = this.getContentResolver().query(selectedImage,
filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Assignments.mulPathArry.add(picturePath);
// Here you will get Path
popup.dismiss();
FileAttachPopUpUtils.this.finish();
}
}
// ///////////////////////////////////////////////////////////////////////
}
#Override
public void onBackPressed() {
return;
}
}

Categories

Resources