I am making an android application that takes image from the camera and saves it in the gallery. What i want is to get path of the saved image. I have tried using intent.getData() but is not working..
I have tried using intent.getData() but is not working..
you Will get intent as NULL in Some Samsung Devices Like Samsung Galaxy S3 with Android OS Version 4.1.1.
i have face this Problems and Solve it by Below way you can try it out if it helps you.
While Calling intent for Image Capture :
String storageState = Environment.getExternalStorageState();
if (storageState.equals(Environment.MEDIA_MOUNTED)) {
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
String filename = System.currentTimeMillis() + ".jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, filename);
mImageCaptureUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
intent.putExtra(
android.provider.MediaStore.EXTRA_OUTPUT,
mImageCaptureUri);
try {
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
} else {
new AlertDialog.Builder(BuildInukshk_4_Camera.this)
.setMessage(
"External Storeage (SD Card) is required.\n\nCurrent state: "
+ storageState)
.setCancelable(true).create().show();
}
} else { // pick from file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Complete action using"), PICK_FROM_FILE);
}
Inside OnActivityResult Method :
case PICK_FROM_CAMERA:
Log.i("TAG", "Inside PICK_FROM_CAMERA");
// Final Code As Below
try {
Log.i("TAG", "inside Samsung Phones");
String[] projection = {
MediaStore.Images.Thumbnails._ID, // The columns we want
MediaStore.Images.Thumbnails.IMAGE_ID,
MediaStore.Images.Thumbnails.KIND,
MediaStore.Images.Thumbnails.DATA };
String selection = MediaStore.Images.Thumbnails.KIND + "=" + // Select
// only
// mini's
MediaStore.Images.Thumbnails.MINI_KIND;
String sort = MediaStore.Images.Thumbnails._ID + " DESC";
// At the moment, this is a bit of a hack, as I'm returning ALL
// images, and just taking the latest one. There is a better way
// to
// narrow this down I think with a WHERE clause which is
// currently
// the selection variable
Cursor myCursor = this.managedQuery(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
projection, selection, null, sort);
long imageId = 0l;
long thumbnailImageId = 0l;
String thumbnailPath = "";
try {
myCursor.moveToFirst();
imageId = myCursor
.getLong(myCursor
.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.IMAGE_ID));
thumbnailImageId = myCursor
.getLong(myCursor
.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID));
thumbnailPath = myCursor
.getString(myCursor
.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.DATA));
} finally {
// myCursor.close();
}
// Create new Cursor to obtain the file Path for the large image
String[] largeFileProjection = {
MediaStore.Images.ImageColumns._ID,
MediaStore.Images.ImageColumns.DATA };
String largeFileSort = MediaStore.Images.ImageColumns._ID
+ " DESC";
myCursor = this.managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
largeFileProjection, null, null, largeFileSort);
String largeImagePath = "";
try {
myCursor.moveToFirst();
// This will actually give yo uthe file path location of the
// image.
largeImagePath = myCursor
.getString(myCursor
.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
mImageCaptureUri_samsung = Uri.fromFile(new File(
largeImagePath));
mImageCaptureUri = null;
} finally {
// myCursor.close();
}
// These are the two URI's you'll be interested in. They give
// you a
// handle to the actual images
Uri uriLargeImage = Uri.withAppendedPath(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
String.valueOf(imageId));
Uri uriThumbnailImage = Uri.withAppendedPath(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
String.valueOf(thumbnailImageId));
// I've left out the remaining code, as all I do is assign the
// URI's
// to my own objects anyways...
} catch (Exception e) {
mImageCaptureUri_samsung = null;
Log.i("TAG",
"inside catch Samsung Phones exception " + e.toString());
}
try {
Log.i("TAG",
"URI Samsung:" + mImageCaptureUri_samsung.getPath());
} catch (Exception e) {
Log.i("TAG", "Excfeption inside Samsung URI :" + e.toString());
}
try {
Log.i("TAG", "URI Normal:" + mImageCaptureUri.getPath());
} catch (Exception e) {
Log.i("TAG", "Excfeption inside Normal URI :" + e.toString());
}
break;
After Running Below Code you Will get Two URIs mImageCaptureUri_samsung and mImageCaptureUri
you will get the mImageCaptureUri as your Path if you are running the App with Simple Devices and you will get your Cpatured Image path in mImageCaptureUri_samsung if you are running with Devices Like Samsung Galaxy S3.
Further you all can go ahead with your Code. it Works For me Very Fine With all the Devices i have tested on.
Also if Someone is having Problem with Above Code than they can reference the Below Great Link Solution of Samsung Galaxy S3
Hope it will Help.
try this one :
public class Camera extends Activity {
private static final int CAMERA_REQUEST = 1888;
private String selectedImagePath;
String fileName = "capturedImage.jpg";
private static Uri mCapturedImageURI;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
TakePhoto();
}
public void TakePhoto()
{
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK)
{
if (requestCode == CAMERA_REQUEST)
{
selectedImagePath = getPath(mCapturedImageURI);
Log.v("selectedImagePath: ", ""+selectedImagePath);
//Save the path to pass between activities
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
This is how I have done:
First create the image uri and with the intent ACTION_IMAGE_CAPTURE pass an extra MediaStore.EXTRA_OUTPUT with this value.
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
capturedImageURI = ImageUtils.takePicture(ReceiptFormActivity.this);
}
});
Then onActivityResult convert this uri path to String path and call the method which will fetch the bitmap from this string path and set it on your imageView.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CONSTANTS.TAKE_PICTURE)
{
if (resultCode == RESULT_OK)
{
if(capturedImageURI != null)
{
Utils.imagePath = ImageUtils.getStringPathFromURI(ReceiptFormActivity.this, capturedImageURI);;
setThumbnail();
}
}
}
}
void setThumbnail()
{
try{
if(Utils.imagePath != null)
{
((TextView)findViewById(R.id.display_image)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
File f = new File(Utils.imagePath);
if(f.exists())
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri imgUri = Uri.fromFile(f);
intent.setDataAndType(imgUri, "image/*");
startActivityForResult(intent,2000);
}
}
});
File imgFilePath = new File(Utils.imagePath);
if(imgFilePath != null && imgFilePath.exists())
{
Bitmap bitmap = ImageUtils.decodeFile(imgFilePath, CONSTANTS.THUMBNAIL_HEIGHT, CONSTANTS.THUMBNAIL_WIDTH);
if(bitmap != null)
{
receipt_thumbnail.setImageBitmap(bitmap);
return;
}
}
}
}
catch (Exception e) {
receipt_thumbnail.setImageResource(R.drawable.some_img);
}
/*
* default img incase of not any exception and no bitmap either.
*/
receipt_thumbnail.setImageResource(R.drawable.some_img);
}
ImageUtils.java
public class ImageUtils {
public static Uri takePicture(Context context)
{
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Receipt_" + System.currentTimeMillis());
Uri mCapturedImageURI = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intentPicture.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
((Activity) context).startActivityForResult(intentPicture,CONSTANTS.TAKE_PICTURE);
return mCapturedImageURI;
}
public static String getStringPathFromURI(Context context, Uri contentUri)
{
try
{
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = context.getContentResolver().query(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();
}
}
public static Bitmap decodeFile(File f, int thumbnailReqHeight, int thumbnailReqWidth)
{
Bitmap b = null;
try {
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream fis = new FileInputStream(f);
BitmapFactory.decodeStream(fis, null, o);
fis.close();
int scale = 1;
if (o.outHeight > thumbnailReqHeight || o.outWidth > thumbnailReqWidth)
{
scale = (int)Math.pow(2, (int) Math.round(Math.log(thumbnailReqHeight / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
}
//Decode with inSampleSize
o.inJustDecodeBounds = false;
o.inSampleSize = scale;
fis = new FileInputStream(f);
b = BitmapFactory.decodeStream(fis, null, o);
fis.close();
} catch (IOException e) {
}
return b;
}
}
The code is very fine. Try giving permission of android.permission.WRITE_EXTERNAL_STORAGE and android.permission.READ_EXTERNAL_STORAGE in android manifest.
Related
I am working on a address book like Android SDK 14+ app. The users should be able to pick an image from the Gallery to add it to a contact entry.
Running the following code to pick and copy the image is no problem in API 14-20 but does not work in API 21+. The file is not found anymore:
protected void pickFoto() {
if (filePermissionsRequired()) {
askForFilePermissions(new PermissionRequestCompletionHandler() {
#Override
public void onPermissionRequestResult(boolean permissionGranted) {
if (permissionGranted)
addOrEditReceipt();
}
});
return;
}
Intent pickPhotoIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhotoIntent , PICK_FOTO_ACTION);
}
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
...
case PICK_FOTO_ACTION: {
Uri imageUri = intent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(imageUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
File imgFile = new File(filePath);
if (imgFile.exists())
// use the file...
else
Toast.makeText(this, "Image file not found", Toast.LENGTH_LONG).show();
break;
}
}
public interface PermissionRequestCompletionHandler {
void onPermissionRequestResult(boolean permissionGranted);
}
private PermissionRequestCompletionHandler permissionRequestCompletionHandler;
public boolean filePermissionsRequired() {
if (Build.VERSION.SDK_INT >= 23)
return checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED;
else
return false;
}
public boolean askForFilePermissions(PermissionRequestCompletionHandler completionHandler) {
if (Build.VERSION.SDK_INT >= 23) {
permissionRequestCompletionHandler = completionHandler;
boolean hasPermission = this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
if (!hasPermission) {
this.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
return true;
}
}
permissionRequestCompletionHandler = null;
return false;
}
The app has runtime permissions to access the Gallery. So what am I doing wrong? How to access the file on newer API versions?
}
try below code to open the camera and getting result:
File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + System.currentTimeMillis() + ".png");
Uri imageUri = Uri.fromFile(file);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, PICK_FOTO_ACTION);
for getting result :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case PICK_FOTO_ACTION: {
Uri imageUri = imageUri;
File imgFile = new File(imageUri.getPath());
if (imgFile.exists())
// use the file...
else
Toast.makeText(this, "Image file not found", Toast.LENGTH_LONG).show();
break;
}
}
}
for getting actual path from uri :
public String getPath(Uri uri)
{
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor == null) return null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String s=cursor.getString(column_index);
cursor.close();
return s;
}
remove unwanted uri part :
public String RemoveUnwantedString(String pathUri){
//pathUri = "content://com.google.android.apps.photos.contentprovider/-1/2/content://media/external/video/media/5213/ORIGINAL/NONE/2106970034"
String[] d1 = pathUri.split("content://");
for (String item1:d1) {
if (item1.contains("media/")) {
String[] d2 = item1.split("/ORIGINAL/");
for (String item2:d2) {
if (item2.contains("media/")) {
pathUri = "content://" + item2;
break;
}
}
break;
}
}
//pathUri = "content://media/external/video/media/5213"
return pathUri;
}
For versions 21 and higher you can do this , you need to add a condition to check the SDK version for this. Exectute this code in the API 21+ condition block.
String wholeID = DocumentsContract.getDocumentId(imageUri );
String id = wholeID.split(":")[1];
String sel = MediaStore.Images.Media._ID + "=?";
cursor =
getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, sel, new String[]{ id }, null);
try
{
int column_index = cursor
.getColumnIndex(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
path = cursor.getString(column_index).toString();
cursor.close();
}
catch(NullPointerException e) {
}
Call the Gallery with belo code
public static final int SELECT_IMAGE_FROM_GALLERY_CODE = 701;
public static void callGallery(Activity activity) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
activity.startActivityForResult(Intent.createChooser(intent, "Complete action using"),
SELECT_IMAGE_FROM_GALLERY_CODE);
}
In OnActivityResult, read URI and read path from uri.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CommonUtils.SELECT_IMAGE_FROM_GALLERY_CODE) {
if (data != null) {
Uri selectedImageUri = data.getData();
// get path from Uri
String imagepath = getPath(this, selectedImageUri);
if (null != imagepath && (!imagepath.isEmpty())) {
// if the image path is not null and not empty, copy image to sdcard
try {
copyDirectoryOrFile(new File(imagepath), new File(myTargetImageFilePath));
} catch (IOException e) {
e.printStackTrace();
}
// load the image into imageView with the help og glide.
loadImageWithGlide(myImageViewContactImage,
myTargetImageFilePath, myDefaultImagePath, myErrorImagePath, false);
} else {
Toast.makeText(this, "Error: Photo selection failed.", Toast.LENGTH_LONG).show();
}
}
}
}
public void loadImageWithGlide(ImageView theImageViewToLoadImage,
String theLoadImagePath, int theDefaultImagePath, int theErrorImagePath,
boolean theIsSkipMemoryCache) {
if (theIsSkipMemoryCache) {
Glide.with(ProfileActivity.this) //passing context
.load(theLoadImagePath) //passing your url to load image.
.placeholder(theDefaultImagePath) //this would be your default image (like default profile or logo etc). it would be loaded at initial time and it will replace with your loaded image once glide successfully load image using url.
.error(theErrorImagePath)//in case of any glide exception or not able to download then this image will be appear . if you won't mention this error() then nothing to worry placeHolder image would be remain as it is.
.diskCacheStrategy(DiskCacheStrategy.ALL) //using to load into cache then second time it will load fast.
//.animate(R.anim.fade_in) // when image (url) will be loaded by glide then this face in animation help to replace url image in the place of placeHolder (default) image.
.centerCrop()
.into(theImageViewToLoadImage); //pass imageView reference to appear the image.
} else {
Glide.with(ProfileActivity.this)
.load(theLoadImagePath)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.centerCrop()
.into(theImageViewToLoadImage);
}
}
public static String getPath(Context theCtx, Uri uri) {
try {
Cursor cursor = (theCtx).getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor.close();
cursor = (theCtx).getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
cursor.moveToFirst();
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
return path;
} catch (Exception e) {
return null;
}
}
public static void copyDirectoryOrFile(File sourceLocation, File targetLocation)
throws IOException {
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists() && !targetLocation.mkdirs()) {
throw new IOException("Cannot create directory " + targetLocation.getAbsolutePath());
}
String[] children = sourceLocation.list();
for (int i = 0; i < children.length; i++) {
copyDirectoryOrFile(new File(sourceLocation, children[i]),
new File(targetLocation, children[i]));
}
} else {
File directory = targetLocation.getParentFile();
if (directory != null && !directory.exists() && !directory.mkdirs()) {
throw new IOException("Cannot create directory " + directory.getAbsolutePath());
}
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
if (out != null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
To load image with glide, add following dependency in app gradle file
compile 'com.github.bumptech.glide:glide:3.7.0'
I want to select multiple images from phone but I am only getting 1 image, now I am using an intent
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), 1);
but still it only selects one image at time .so how can I set a limit on image selection more than 1 and how I can handle it in onActivityResult.
Firstly,
Which action you need to perform with multiple image,that is important
Secondly you can use Array list for same,array list of bitmap and pass that list further and you can access all that images from that list..Pls try and revert..
Try below code:
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), 1);
//Override onActivityResult method
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode ==1)
if (data != null) {
ClipData clipData = null;
try {
clipData = data.getClipData();
} catch (Exception exception) {
e.printStackTrace();
}
if (clipData != null) {
for (int i = 0; i < clipData.getItemCount();i++) {
// Get Uri for the image
Uri selectedImage = data.getClipData().getItemAt(i).getUri();
try {
String imagePath = getRealPathFromURI(selectedImage, this); /* Do whatever you want to do with imagePath */
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
private String getRealPathFromURI(Uri contentURI, Context context) {
String filePath = "";
Pattern p = Pattern.compile("(\\d+)$");
Matcher m = p.matcher(contentURI.toString());
if (!m.find()) {
Log.e("", "ID for requested image not found: " + contentURI.toString());
return filePath;
}
String imgId = m.group();
String[] column = { MediaStore.Images.Media.DATA };
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{imgId}, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
}
in my project i want to store image in DB Sqlite, but i have problem when i want to displaying image, please help me, this is my code to select image :
public void bt_UFotoClick(View v)
{
v = Img;
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),SELECT_PICTURE);
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if(requestCode == 1)
{
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = intent.getData();
String selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
imageDetail.setVisibility(View.VISIBLE);
imageDetail.setImageURI(selectedImageUri);
SQLiteDatabase dbUpdate = dbHelper.getWritableDatabase();
byte[] byteImage1 = null;
try {
FileInputStream instream = new FileInputStream(selectedImagePath);
BufferedInputStream bif = new BufferedInputStream(instream);
byteImage1 = new byte[bif.available()];
bif.read(byteImage1);
dbUpdate.execSQL("update m_item set image = '"+byteImage1+"' where kd='"+Code_I+"'");
System.out.println("Success. ");
System.out.println("Success. " +byteImage1);
} catch (IOException e) {
System.out.println("Error. "+e.getMessage());
}
}
else if (resultCode == RESULT_CANCELED)
{
}
}
}
#SuppressWarnings("deprecation")
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
And to Displaying image again i use this code :
SearchDetail = db.rawQuery("SELECT * FROM m_item where kd = '"+GetId+"'",null);
if(SearchDetail .getCount()>=1) {
SearchDetail .moveToFirst();
byte GBR_II[]= SearchDetail.getBlob(SearchDetail.getColumnIndex("image"));
imageDetail.setImageBitmap(BitmapFactory.decodeByteArray(GBR_II, 0,GBR_II.length));
System.out.println("get : "+GBR_II);
}
But image not display and in logcat : 12-09 02:28:50.977: D/skia(561): --- SkImageDecoder::Factory returned null
Thanks,
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
filePath = getOutputMediaFile(FileColumns.MEDIA_TYPE_IMAGE);
File file = new File(filePath);
Uri output = Uri.fromFile(file);
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, output);
startActivityForResult(i, RETURN_FILE_PATH);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//data is always null here.
//requestCode = RETURN_FILE_PATH;
//resultCode = Activity.RESULT_OK;
}
I checked the values for file and output Uri, both are fine and the captured image actually exists at that location.
But the data returned in onActivityResult is always null even after capturing the image.
EDIT:
I checked this question:
onActivityResult returns with data = null
which says:
Whenever you save an image by passing EXTRAOUTPUT with camera intent
the data parameter inside the onActivityResult always return null. So,
instead of using data to retrieve the image , use the filepath to
retrieve the Bitmap.
and maybe that solution will work for me. But the above code of mine was a working code until now for the same scenario.
According to this post data is null when you pre insert a uri. That means you already defined your output uri here:
i.putExtra(MediaStore.EXTRA_OUTPUT, output);
So when you get a Activity.RESULT_OK; just load the taken photo by its known url.
Try this code this is working for me.
else if(requestCode == Constant.PICK_FROM_CAMERA)
{
if (resultCode == Activity.RESULT_OK)
{
if(data!=null)
{
mImageCaptureUri = data.getData();
//path= mImageCaptureUri.getPath();
try
{
path = getPath(mImageCaptureUri,Wonderlistpage.this); //from Gallery
}
catch(Exception e)
{
path = mImageCaptureUri.getPath();
Log.i("check image attach or not", e.toString());
}
String arr[] = path.split("/");
int i;
String k = null;
for(i=0;i<arr.length;i++)
{
k=arr[i];
}
photoname="_"+String.valueOf(System.currentTimeMillis()) +k;
if(setprofileimage_sendimagewithmessage==1)
{
performCrop(mImageCaptureUri);
}
else
{
loading_details="CAMERA";
new performBackgroundTask33().execute();
}
}
else
{
file1 = new File(Environment.getExternalStorageDirectory(),
String.valueOf(System.currentTimeMillis()) + "_FromCamera.jpg");
Uri mImageCaptureUri = Uri.fromFile(file1);
try
{
path = getPath(mImageCaptureUri,Wonderlistpage.this); //from Gallery
}
catch(Exception e)
{
path = mImageCaptureUri.getPath();
Log.i("check image attach or not", e.toString());
}
String arr[] = path.split("/");
int i;
String k = null;
for(i=0;i<arr.length;i++)
{
k=arr[i];
}
photoname="_"+String.valueOf(System.currentTimeMillis()) +k;
if(setprofileimage_sendimagewithmessage==1)
{
performCrop(mImageCaptureUri);
}
else
{
loading_details="CAMERA";
new performBackgroundTask33().execute();
}
}
//new UploadTask().execute();
}
}
Try following code
{
final String[] imageColumns = { MediaStore.Images.Media._ID,MediaStore.Images.Media.DATA };
final String imageOrderBy = MediaStore.Images.Media._ID + " DESC";
Cursor imageCursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageColumns, null, null, imageOrderBy);
imageCursor.moveToFirst();
do {
String fullPath = imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
if (fullPath.contains("DCIM")) {
//get bitmap from fullpath here.
return;
}
}
while (imageCursor.moveToNext());
Just Put this code into your onActivityResult. The same problem i have faced on some devices and this solved my problem. Hope this will also help you.
try {
Uri selectedImage = output;
if (selectedImage == null)
return;
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();
} catch (Exception e) {
return;
}
You will get the Picture path in picturePath variable and Uri in selectedImage Variable.
If your activity has launchmode as singleInstance in your manifest then you would face this issue. Try changing it. As it cancels the result everytime.
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