In my application ,on clicking Image View i want to start Camera which will capture image and display it in another image view.My code is given below:
//On clicking Camera
iv_camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
if (data != null) {
Log.e("Result Code", String.valueOf(resultCode));
Bitmap photo = (Bitmap) data.getExtras().get("data");
Uri selectedImageUri = data.getData();
Log.e("ImageUri", String.valueOf(selectedImageUri));
String realPath = getRealPathFromURI(selectedImageUri);
Log.e("Real Path", realPath);
imgProfilePic.setImageBitmap(photo);
}
}
}
//Get real path form Uri
public String getRealPathFromURI(Uri contentUri) {
try {
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} catch (Exception e) {
return contentUri.getPath();
}
}
My problem is that ,on some mobiles it is working fine but on some it is not. For example: If i am testing my application using on my phone Yu Yureka having Lollipop ,it is giving me data as null.Also when the orientation changes,application is crashing .Please help me to fix the issue.
In your Manifest file use these permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Implement from this Simple Code Example this is my working example code
public void CameraClick(View v) {
Intent intent= new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// creating Dir to save clicked Photo
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/cam_Intent");
myDir.mkdirs();
// save clicked pic to given dir with given name
File file = new File(Environment.getExternalStorageDirectory(),
"/cam_Intent/MyPhoto.jpg");
outPutfileUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outPutfileUri);
startActivityForResult(intent, TAKE_PIC);
}
Bitmap bitmap = null;
#Override
protected void onActivityResult(int requestCode, int resultCode,Intent data)
{
if (requestCode == TAKE_PIC && resultCode==RESULT_OK) {
String uri = outPutfileUri.toString();
Log.e("uri-:", uri);
Toast.makeText(this, outPutfileUri.toString(),Toast.LENGTH_LONG).show();
//Bitmap myBitmap = BitmapFactory.decodeFile(uri);
// mImageView.setImageURI(Uri.parse(uri)); OR drawable make image strechable so try bleow also
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), outPutfileUri);
Drawable d = new BitmapDrawable(getResources(), bitmap);
mImageView.setImageDrawable(d);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Related
i tried to set on imageview with original quality but the image get compressed.
please help me to set image in imageview with original quality.
ImageView imageView;
private static final int CAMERA_REQUEST = 1888;
Bitmap photo;
uploadImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST) {
if(data!=null) {
photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
}
Try using glide, first in your gradle add dependency
compile 'com.github.bumptech.glide:glide.3.7.0'
And use this code to get capture images
values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "From your 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, PICTURE_RESULT);
And then in onActivityResult
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICTURE_RESULT:
if (requestCode == PICTURE_RESULT)
if (resultCode == Activity.RESULT_OK) {
try {
thumbnail = MediaStore.Images.Media.getBitmap(
getContentResolver(), imageUri);
imgView.setImageBitmap(thumbnail);
imageurl = getRealPathFromURI(imageUri);
Imageview imageView = (ImageView) findViewById(R.id.image_view);
Glide.with(this).load(imageurl).into(imageView);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
And to get the path of image
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
I need to take a photo from my app and display it on an imageView, so now I´m using an intent request:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
bm = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(bm);
}
}
}
The problem is that this code gets the thumbail of the image, not the image itself in full resollution, and I don´t know how to get it. I´ve searched and I have found this https://developer.android.com/training/camera/photobasics.html , but as I´m starting with this i don´t understand it.
Could somebody help me please?
Before you call CameraIntent create a file and uri based on that filepath as shown here.
filename = Environment.getExternalStorageDirectory().getPath() + "/test/testfile.jpg";
imageUri = Uri.fromFile(new File(filename));
// start default camera
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
imageUri);
startActivityForResult (cameraIntent, CAMERA_PIC_REQUEST);
Now, you have the filepath you can use it in onAcityvityResult method as following,
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode != CAMERA_PIC_REQUEST || filename == null)
return;
ImageView img = (ImageView) findViewById(R.id.image);
img.setImageURI(imageUri);
Try out this code, It works for me.
Open camera using below code:
Intent intent = new Intent();
try {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)&& !Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED_READ_ONLY)) {
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator+ ".your folder name"
+ File.separator + "picture").getPath());
if (!file.exists()) {
file.mkdirs();
}
capturedImageUri = Uri.fromFile(File.createTempFile("your folder name" + new SimpleDateFormat("ddMMyyHHmmss", Locale.US).format(new Date()), ".jpg", file));
intent.putExtra(MediaStore.EXTRA_OUTPUT, capturedImageUri);
startActivityForResult(intent, Util.REQUEST_CAMERA);
} else {
Toast.show(getActivity(),"Please insert memory card to take pictures and make sure it is write able");
}
} catch (Exception e) {
e.printStackTrace();
}
In onActivityResult retrieve path of captured image:
try {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) && !Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED_READ_ONLY)) {
File file = new File(Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator
+ ".captured_Images"+ File.separator+ "picture").getPath());
if (!file.exists()) {
file.mkdirs();
}
selectedPath1 = capturedImageUri.toString().replace("file://", "");
Logg.e("selectedPath1", "OnactivityResult==>>" + selectedPath1);
imageLoader.displayImage(capturedImageUri.toString(), imgCarDetails1);
} else {
Toast.show(getActivity(), "Please insert memory card to take pictures and make sure it is write able");
}
} catch (Exception e) {
e.printStackTrace();
}
Add this permission in Manifest file:-
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
None of the answers worked for me, and I couldn´t use the tutorial as when creating the FileProvider, the xml gives me an error.
Finally I found this answer which works like a charm. Android Camera Intent: how to get full sized photo?
I have an app that can make pictures and upload them. The upload requires the file path of the photo but I can't get it.
This is my code:
public void maakfoto (View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
knop.setVisibility(Button.VISIBLE);
System.out.println(mImageCaptureUri);
}
}
Please help me to get the file path.
Posting to Twitter needs the image's actual path on the device to be sent in the request to post. I was finding it mighty difficult to get the actual path and more often than not I would get the wrong path.
To counter that, once you have a Bitmap, I use that to get the URI from using the getImageUri(). Subsequently, I use the tempUri Uri instance to get the actual path as it is on the device.
This is production code and naturally tested. ;-)
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
knop.setVisibility(Button.VISIBLE);
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
Uri tempUri = getImageUri(getApplicationContext(), photo);
// CALL THIS METHOD TO GET THE ACTUAL PATH
File finalFile = new File(getRealPathFromURI(tempUri));
System.out.println(mImageCaptureUri);
}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
Try out with mImageCaptureUri.getPath(); By Below Way :
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
//Get your Image Path
String Path=mImageCaptureUri.getPath();
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
knop.setVisibility(Button.VISIBLE);
System.out.println(mImageCaptureUri);
}
In order to take a picture you have to determine a path where you would like the image saved and pass that as an extra in the intent, for example:
private void capture(){
String directoryPath = Environment.getExternalStorageDirectory() + "/" + IMAGE_DIRECTORY + "/";
String filePath = directoryPath+Long.toHexString(System.currentTimeMillis())+".jpg";
File directory = new File(directoryPath);
if (!directory.exists()) {
directory.mkdirs();
}
this.capturePath = filePath; // you will process the image from this path if the capture goes well
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra( MediaStore.EXTRA_OUTPUT, Uri.fromFile( new File(filePath) ) );
startActivityForResult(intent, REQUEST_CAPTURE);
}
I just copied the above portion from another answer I gave.
However to warn you there are a lot of inconsitencies with image capture behavior between devices that you should look out for.
Here is an issue I ran into on some HTC devices, where it would save in the location I passed and in it's default location resulting in duplicate images on the device:
Deleting a gallery image after camera intent photo taken
I am doing this on click of Button.
private static final int CAMERA_PIC_REQUEST = 1;
private View.OnClickListener OpenCamera=new View.OnClickListener() {
#Override
public void onClick(View paramView) {
// TODO Auto-generated method stub
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
NewSelectedImageURL=null;
//outfile where we are thinking of saving it
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
String newPicFile = RecipeName+ df.format(date) + ".png";
String outPath =Environment.getExternalStorageDirectory() + "/myFolderName/"+ newPicFile ;
File outFile = new File(outPath);
CapturedImageURL=outFile.toString();
Uri outuri = Uri.fromFile(outFile);
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, outuri);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
};
You can get the URL of the recently Captured Image from variable CapturedImageURL
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//////////////////////////////////////
if (requestCode == CAMERA_PIC_REQUEST) {
// do something
if (resultCode == RESULT_OK)
{
Uri uri = null;
if (data != null)
{
uri = data.getData();
}
if (uri == null && CapturedImageURL != null)
{
uri = Uri.fromFile(new File(CapturedImageURL));
}
File file = new File(CapturedImageURL);
if (!file.exists()) {
file.mkdir();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+Environment.getExternalStorageDirectory())));
}
}
}
use this function to get the capture image path
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Uri mImageCaptureUri = intent.getData();
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
knop.setVisibility(Button.VISIBLE);
System.out.println(mImageCaptureUri);
//getImgPath(mImageCaptureUri);// it will return the Capture image path
}
}
public String getImgPath(Uri uri) {
String[] largeFileProjection = { MediaStore.Images.ImageColumns._ID,
MediaStore.Images.ImageColumns.DATA };
String largeFileSort = MediaStore.Images.ImageColumns._ID + " DESC";
Cursor myCursor = this.managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
largeFileProjection, null, null, largeFileSort);
String largeImagePath = "";
try {
myCursor.moveToFirst();
largeImagePath = myCursor
.getString(myCursor
.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
} finally {
myCursor.close();
}
return largeImagePath;
}
You can do like that In Kotlin If you need kotlin code in the future
val myUri = getImageUri(applicationContext, myBitmap!!)
val finalFile = File(getRealPathFromURI(myUri))
fun getImageUri(inContext: Context, inImage: Bitmap): Uri {
val bytes = ByteArrayOutputStream()
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes)
val path = MediaStore.Images.Media.insertImage(inContext.contentResolver, inImage, "Title", null)
return Uri.parse(path)
}
fun getRealPathFromURI(uri: Uri): String {
val cursor = contentResolver.query(uri, null, null, null, null)
cursor!!.moveToFirst()
val idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA)
return cursor.getString(idx)
}
To get the path of all images in android I am using following code
public void allImages()
{
ContentResolver cr = getContentResolver();
Cursor cursor;
Uri allimagessuri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Images.Media._ID + " != 0";
cursor = cr.query(allsongsuri, STAR, selection, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
String fullpath = cursor.getString(cursor
.getColumnIndex(MediaStore.Images.Media.DATA));
Log.i("Image path ", fullpath + "");
} while (cursor.moveToNext());
}
cursor.close();
}
}
Simple Pass Intent first
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
And u will get picture path on u onActivityResult
#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();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
I have one problem. When I try to get picture from camera, the quality is very low.
At first, capture the picture using camera, than save to the directory and at the same time get that picture and show in my app.The picture saved inside directory is a fine quality but when I get it from directory, the quality is low. below is my sample code :
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == CAMERA_PIC_REQUEST) {
Bitmap thumbnail = (Bitmap) intent.getExtras().get("data");
if (g==1)
{
ImageView myImage = (ImageView) findViewById(R.id.img5);
myImage.setImageBitmap(thumbnail);
View a = findViewById(R.id.img5);
a.setVisibility(View.VISIBLE);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byteArray1 = stream.toByteArray();
}
}
any solution/suggestion?
Thanks :)
Solved
The problem solved when I follow the code given by Antrromet below
I have used the following code and this works perfectly fine for me.
values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "From your 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, PICTURE_RESULT);
and also
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICTURE_RESULT:
if (requestCode == PICTURE_RESULT)
if (resultCode == Activity.RESULT_OK) {
try {
thumbnail = MediaStore.Images.Media.getBitmap(
getContentResolver(), imageUri);
imgView.setImageBitmap(thumbnail);
imageurl = getRealPathFromURI(imageUri);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
and
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
I will give you something that work for me. I asked the same !
Solution to save a picture in a specific folder without lost quality
I FOUND THE SOLUTION:
//Create a new folder code:
String path = String.valueOf(Environment.getExternalStorageDirectory()) + "/your_name_folder";
try {
File ruta_sd = new File(path);
File folder = new File(ruta_sd.getAbsolutePath(), nameFol);
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
if (success) {
Toast.makeText(MainActivity.this, "Carpeta Creada...", Toast.LENGTH_SHORT).show();
}
} catch (Exception ex) {
Log.e("Carpetas", "Error al crear Carpeta a tarjeta SD");
}
Intent i = new Intent(MainActivity.this, MainActivity.class);
startActivity(i);
finish();//agregue este
//Method to take a Picture
public void clickFoto(View view) {
takePic();
}
//takePic()
private void takePic() {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
*File file = new File(Environment.getExternalStorageDirectory(), "/your_name_folder/a" + "/photo_" + timeStamp + ".png");*
imageUri = Uri.fromFile(file);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, PICTURE_RESULT);
}
//onActivityResult
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICTURE_RESULT:
if (requestCode == PICTURE_RESULT)
if (resultCode == Activity.RESULT_OK) {
try {
Bitmap thumbnail = MediaStore.Images.Media.getBitmap(
getContentResolver(), imageUri);
imgFoto.setImageBitmap(thumbnail);
imageurl = getRealPathFromURI(imageUri);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
// getRealPathFromUri
public String getRealPathFromURI(Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
Add the photo to a gallery
.
.
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(currentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
for more detail : https://developer.android.com/training/camera/photobasics.html
I am using this code to fetch Image from gallery:
fromGalleryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
canvasPictureDialog.dismiss();
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
//startActivity(intent);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),10);
//finish();
}
});
And to take image from camera i use this code:
private static final int TAKE_PHOTO_CODE = 1;
private void takePhoto(){
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(this)) );
startActivityForResult(intent, TAKE_PHOTO_CODE);
}
private File getTempFile(Context context){
//it will return /sdcard/image.tmp
//final File path = new File( Environment.getExternalStorageDirectory(), context.getPackageName() );
final File path = new File( Environment.getExternalStorageDirectory(), context.getPackageName());
if(!path.exists()){
path.mkdir();
}
return new File(path, "image.tmp");
}
And common code for onActivityResult is:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 10 && resultCode == Activity.RESULT_OK) {
Uri contentUri = data.getData();
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
imagePath = cursor.getString(column_index);
//Bitmap croppedImage = BitmapFactory.decodeFile(imagePath);
tempBitmap = BitmapFactory.decodeFile(imagePath);
photoBitmap = Bitmap.createScaledBitmap(tempBitmap, display.getWidth(), display.getHeight(), true);
}
if(resultCode == RESULT_OK && requestCode==TAKE_PHOTO_CODE){
final File file = getTempFile(this);
try {
tempBitmap = Media.getBitmap(getContentResolver(), Uri.fromFile(file) );
photoBitmap = Bitmap.createScaledBitmap(tempBitmap, display.getWidth(), display.getHeight(), true);
// do whatever you want with the bitmap (Resize, Rename, Add To Gallery, etc)
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Now with using this code i am drawing the image on canvas:
if(!(imagePath==null))
{
//tempBitmap = BitmapFactory.decodeFile(imagePath);
//photoBitmap = Bitmap.createScaledBitmap(tempBitmap, display.getWidth(), display.getHeight(), true);
canvas.drawBitmap (photoBitmap,0, 0, null);
}
But with that use, I am able to get Image from gallery but not from the camera. Why ??
Whats wrong in my code ??
Thanks.
Well, I have solve this problem for my own way.
There is a logical mistake. I have taken the if condition on imagePath variable which can not works for the taking image from camera.
I have taken one boolean Variable and set it for Taking Image from Camera and it works for me.
Anyway, Thanks for the Comments and help.
Thanks.