I'm trying to upload an image to server that was took from my camera. In this process while I try to decode the image, it throws me File not found exception. Please help me fixing this issue:
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File file123 = new File(Environment
.getExternalStorageDirectory()
+ "/sdcard/BusinessVibes/", "IMG_" + timeStamp
+ ".jpg");
tempURI = Uri.fromFile(file123);
Log.i("tempURI", "tempURI: " + tempURI);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempURI);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
dialog1.dismiss();
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Log.i("camera intent", "camera intent");
Log.i("temp uri", "temp uri: " + tempURI.toString());
decodeFile(tempURI.toString());
UploadImage_textView.setEnabled(true);
// new ImageUploadTask(encoded).execute();
}
}
public void decodeFile(String filePath) {
// Decode image size
Log.i("decodeFile", "sellDetails_productName: " + filePath);
Log.i("$$$$$$$$$$$$$$$$$$$", "$$$$$$$$$$$$$$$$$");
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o); // file not found exception is thrown in this line
// The new size we want to scale to final
int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
Log.i("width_tmp", "width_tmp: " + width_tmp);
Log.i("height_tmp", "height_tmp: " + height_tmp);
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
Above is the code for my reference. When I tried checking the path in my mobile the image exists. Please help me resolving the issue.
You should try.
onActivityResult();
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 imgPath = cursor.getString(columnIndex);
cursor.close();
Try this:
Intent cameraIntent= new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
Uri outputfile=Uri.fromFile(Environment.getExternalStorageDirectory()
+ "/image/"+timeStamp ;);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputfile);
if(intent.resolveActivity(getPackageManager())!=null)
startActivityForResult(intent, CAMERA_REQUEST_3);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST_1 && resultCode == RESULT_OK ) {
Bitmap capturedImage = new BitmapLoader().loadBitmap(defaultPath, 250, 200);
img1.setImageBitmap(capturedImage);
File folder = new File(Environment.getExternalStorageDirectory().toString()
+ "/image/"+timeStamp );
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
listOfFiles[i].delete();
if(Build.VERSION.SDK_INT != Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT != Build.VERSION_CODES.LOLLIPOP)
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,Uri.parse("file://"+Environment.getExternalStorageDirectory()+ "/image/")));
else
{
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(folder);
mediaScanIntent.setData(contentUri);
sendBroadcast(mediaScanIntent);
}
}
}
public static Bitmap loadBitmap(String filePath,int requiredWidth,int requiredHeight){
BitmapFactory.Options options= getOptions(filePath,requiredWidth, requiredHeight);
options.inMutable=true;
Bitmap capturedImage = BitmapFactory.decodeFile(filePath,options);
Canvas canvas = new Canvas(capturedImage);
return capturedImage;
}
Related
I want to capture an image using camera and store it in server. But I am getting null pointer exception after capturing the image. Completed mostly but this error is annoying. I am newbie to android i don't know why this error occurs. Need help thanks in advance
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == CAMERA) {
if (data == null) {
Snackbar.make(parentView, R.string.string_unable_to_pick_image, Snackbar.LENGTH_INDEFINITE).show();
return;
}
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
// 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));
decodeFile(finalFile.toString());}}
**getImageUri method **
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "aadhar", null);
return Uri.parse(path);//getting error here
}
getRealPathFromURI Method
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);
}
decodeFile Method
public void decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
Bitmap bitmap = BitmapFactory.decodeFile(filePath, o2);
imageView.setImageBitmap(bitmap);
}
Error
Caused by: java.lang.NullPointerException: uriString
at android.net.Uri$StringUri.<init>(Uri.java:475)
at android.net.Uri$StringUri.<init>(Uri.java)
at android.net.Uri.parse(Uri.java:437)
at com.androidbuts.ui.MainActivity.getImageUri(MainActivity.java:274)
at com.androidbuts.ui.MainActivity.onActivityResult(MainActivity.java:233)
at android.app.Activity.dispatchActivityResult(Activity.java:7139)
<!--First define permissions in Menifest-->
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
// open camera as
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA);
// Then Retrive image As
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA && data != null) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
File imageStorageDir = new File(Environment.getExternalStorageDirectory(),
getResources().getString(R.string.app_name));
if (!imageStorageDir.exists()) {
imageStorageDir.mkdirs();
}
imagePath = imageStorageDir + File.separator + "_NAME_YOU_WISH" + ".jpg";
fileImage = new File(imagePath); // FILE
try {
FileOutputStream out = new FileOutputStream(imagePath);
photo.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
if (fileImage != null) {
if (fileImage.isFile() && fileImage.exists()) {
// MyApplication.log(LOG_TAG, "onActivityResult() SHOWING IMAGE BY GLIDE, fileImage:-> " + fileImage.getAbsolutePath());
Glide.with(context)
.load(fileImage.getAbsoluteFile())
.asBitmap()
.placeholder(R.drawable.ic_broken_image)
.into(img_camera);
}
}
} catch (Exception e) {
//MyApplication.log(LOG_TAG, "onActivityResult() , Exception: " + e.getMessage());
}
}
}
// CALL THE FUNCTION TO SEND IMAGE TO SERVER
public void callSendCheckReport() {
MyApplication.showDialog(context, "Please Wait...");
HashMap<String, Object> map = new HashMap<>();
map.put("date", today);
map.put("salesman_id", MyApplication.get_session(MyApplication.SESSION_SALESMAN_ID));
if (actionStatus.equals("do_CHECK_IN")) { //// do_CHECK_IN, do_NO_CHANGE, do_CHECK_OUT
map.put("checkin", "yes");
map.put("in_time", checkTimeStamp);
if (fileImage != null)
map.put("in_image", new TypedFile("image*//*", fileImage));
}
RestClient.getWebServices().sendCheckReport(map,
new Callback<String>() {
#Override
public void success(String s, Response response) {
MyApplication.log(LOG_TAG, "Responce is----> " + s);
try {
JSONObject res = new JSONObject(s); // "status":"TRUE","message":"Shop Registered Successfully."}
String status = res.getString("status");
String message = res.getString("message");
MyApplication.stopLoading();
if (status.equals("TRUE")) {
if (fileImage.exists())
fileImage.delete();
}
showDialogBox(context, getResources().getString(R.string.app_name), message);
} catch (JSONException e) {
MyApplication.stopLoading();
// MyApplication.log(LOG_TAG + "RESPONSE JSONException ->" + e.getMessage());
}
}
#Override
public void failure(RetrofitError error) {
MyApplication.log(LOG_TAG + " RetrofitError ->" + error.getMessage());
MyApplication.stopLoading();
}
});
}
I'm tyring to upload an image for my application, here when I choose an Image from my Gallery it works fine, now If I select the same image from "Recent" folder the picture path is null and I'm unable to upload the image. Can you please help me resolving this issue.
Here's my code for your reference:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// find the views
image = (ImageView) findViewById(R.id.uploadImage);
uploadButton = (Button) findViewById(R.id.uploadButton);
takeImageButton = (Button) findViewById(R.id.takeImageButton);
selectImageButton = (Button) findViewById(R.id.selectImageButton);
selectImageButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
selectImageFromGallery();
}
});
takeImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
/*
* Picasso.with(MainActivity.this) .load(link) .into(image);
*/
}
});
// when uploadButton is clicked
uploadButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// new ImageUploadTask().execute();
Toast.makeText(MainActivity.this, "clicked", Toast.LENGTH_SHORT)
.show();
uploadTask();
}
});
}
protected void uploadTask() {
// TODO Auto-generated method stub
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
String file = Base64.encodeToString(data, 0);
Log.i("base64 string", "base64 string: " + file);
new ImageUploadTask(file).execute();
}
/**
* Opens dialog picker, so the user can select image from the gallery. The
* result is returned in the method <code>onActivityResult()</code>
*/
public void selectImageFromGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),
PICK_IMAGE);
}
/**
* Retrives the result returned from selecting image, by invoking the method
* <code>selectImageFromGallery()</code>
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
Log.i("selectedImage", "selectedImage: " + selectedImage.toString());
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
/*
* Cursor cursor = managedQuery(selectedImage, filePathColumn, null,
* null, null);
*/
cursor.moveToFirst();
// int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
int columnIndex = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String picturePath = cursor.getString(columnIndex);
Log.i("picturePath", "picturePath: " + picturePath);
cursor.close();
decodeFile(picturePath);
}
}
public void decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFile(filePath, o2);
image.setImageBitmap(bitmap);
}
Here's my log for your reference:
use this to display image in ImageView
Uri selectedImage = data.getData();
imgView.setImageUri(selectedImage);
OR use this..
Bitmap reducedSizeBitmap = getBitmap(selectedImage.getPath());
imgView.setImageBitmap(reducedSizeBitmap);
if you want to reduce the image size and also want to get bitmap
private Bitmap getBitmap(String path) {
Uri uri = Uri.fromFile(new File(path));
InputStream in = null;
try {
final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
in = getContentResolver().openInputStream(uri);
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, o);
in.close();
int scale = 1;
while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
IMAGE_MAX_SIZE) {
scale++;
}
Bitmap b = null;
in = getContentResolver().openInputStream(uri);
if (scale > 1) {
scale--;
// scale to max possible inSampleSize that still yields an image
// larger than target
o = new BitmapFactory.Options();
o.inSampleSize = scale;
b = BitmapFactory.decodeStream(in, null, o);
// resize to desired dimensions
int height = b.getHeight();
int width = b.getWidth();
double y = Math.sqrt(IMAGE_MAX_SIZE
/ (((double) width) / height));
double x = (y / height) * width;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
(int) y, true);
b.recycle();
b = scaledBitmap;
System.gc();
} else {
b = BitmapFactory.decodeStream(in);
}
in.close();
Matrix matrix = new Matrix();
//set image rotation value to 90 degrees in matrix.
matrix.postRotate(90);
//supply the original width and height, if you don't want to change the height and width of bitmap.
b = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), matrix, true);
return b;
} catch (IOException e) {
Log.e("", e.getMessage(), e);
return null;
}
}
I ran into this same problem. While there are other ways to consume the URI, there is also a way to get the correct path.
See this issue:
retrieve absolute path when select image from gallery kitkat android
It's a bit outdated. Here's updated code.
Uri originalUri = data.getData();
final int takeFlags = data.getFlags()
& (Intent.FLAG_GRANT_READ_URI_PERMISSION
| Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
// Check for the freshest data.
getContentResolver().takePersistableUriPermission(originalUri, takeFlags);
/* now extract ID from Uri path using getLastPathSegment() and then split with ":"
then call get Uri to for Internal storage or External storage for media I have used getUri()
*/
String id = originalUri.getLastPathSegment().split(":")[1];
final String[] imageColumns = {MediaStore.Images.Media.DATA};
final String imageOrderBy = null;
Uri uri = getUri();
String filePath = "path";
Cursor imageCursor = getContentResolver().query(uri, imageColumns,
MediaStore.Images.Media._ID + "=" + id, null, imageOrderBy);
if(imageCursor.moveToFirst()) {
filePath = imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
}
private Uri getUri() {
String state = Environment.getExternalStorageState();
if(!state.equalsIgnoreCase(Environment.MEDIA_MOUNTED))
return MediaStore.Images.Media.INTERNAL_CONTENT_URI;
return MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}
Make sure you have the read external storage permission. Also, note that the way you have it written worked pre-kitkat. Unfortunately, most examples still seem to use that method even though it's no longer guaranteed to work.
I hade same problem and found this solution from this github sample https://github.com/maayyaannkk/ImagePicker
This is the solution for your issue
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String imageEncoded = getRealPathFromURI(getActivity(), selectedImageUri);
Bitmap selectedImage = BitmapFactory.decodeFile(imageString);
image.setImageBitmap(selectedImage);
}
}
These method use for get image url
public String getRealPathFromURI(Context context, Uri contentUri) {
OutputStream out;
File file = new File(getFilename(context));
try {
if (file.createNewFile()) {
InputStream iStream = context != null ? context.getContentResolver().openInputStream(contentUri) : context.getContentResolver().openInputStream(contentUri);
byte[] inputData = getBytes(iStream);
out = new FileOutputStream(file);
out.write(inputData);
out.close();
return file.getAbsolutePath();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private byte[] getBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
private String getFilename(Context context) {
File mediaStorageDir = new File(context.getExternalFilesDir(""), "patient_data");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
mediaStorageDir.mkdirs();
}
String mImageName = "IMG_" + String.valueOf(System.currentTimeMillis()) + ".png";
return mediaStorageDir.getAbsolutePath() + "/" + mImageName;
}
While selecting an image from a gallery in my application it doesn't crash but instead its unable to decode the stream of the path. Taking the picture directly from the camera is working fine but from the gallery its not here is my code in my activity result .
//enter code here
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri selectedImageUri = null;
String filePath = null;
switch (requestCode) {
case PICK_IMAGE:
if (resultCode == Activity.RESULT_OK)
{
selectedImageUri = data.getData();
name = getPath(selectedImageUri);
}
break;
case PICK_Camera_IMAGE:
if (resultCode == RESULT_OK) {
//use imageUri here to access the image
selectedImageUri = imageUri;
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
}
break;
}
if(selectedImageUri != null)
{
try
{
// OI FILE Manager
String filemanagerstring = selectedImageUri.getPath();
// MEDIA GALLERY
String selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null) {
filePath = selectedImagePath;
} else if (filemanagerstring != null) {
filePath = filemanagerstring;
} else {
Toast.makeText(getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG).show();
Log.e("Bitmap", "Unknown path");
}
if (filePath != null)
{
decodeFile(filePath);
} else {
bitmap = null;
}
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(), "Internal error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
}
public String getPath(Uri uri)
{
// just some safety built in
if( uri == null ) {
// TODO perform some logging or show user feedback
return null;
}
// try to retrieve the image from the media store first
// this will only work for images selected from gallery
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if( cursor != null ){
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
// this is our fallback here
return uri.getPath();
}
public void decodeFile(String filePath)
{
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true)
{
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFile(filePath, o2);
//imgView.setImageBitmap(bitmap);
}
any help would be appreciated.
In later versions of Android (KitKat and above), the format of Uris returned from the gallery picker has changed, and it's not always possible to get a file path from a Uri without a lot of hassle, and sometimes it's not possible at all. So, it's better just to decode the bitmap using the Uri directly.
Change your decodeFile() function to accept a Uri and decode the image using BitmapFactory.decodeStream(), like this:
public void decodeFile(Uri fileUri)
{
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(getContentResolver().openInputStream(fileUri), null, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true)
{
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(fileUri), null, o2);
//imgView.setImageBitmap(bitmap);
}
Then you can simplify your onActivityResult() code to this:
if(selectedImageUri != null)
{
try
{
decodeFile(selectedImageUri);
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(), "Internal error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
If you have problems obtaining a valid Uri, see the accepted answer for this question for how to obtain a Uri inside OnActivityResult() with correct permissions on KitKat and above.
Well I choose another approach for this thing. You cannot diffrentiate between you chose a picture from gallery or from a Camera Intent.
Here is my code.
public class Chooser extends Activity {
ImageView imageView1;
private Uri outputFileUri;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);
imageView1 = (ImageView) this.findViewById (R.id.imageView1);
Button frag1 = (Button) this.findViewById (R.id.frag1);
frag1.setOnClickListener (new OnClickListener () {
#Override
public void onClick (View v) {
choosePic (null);
}
});
}
public void choosePic (View view) {
// Determine Uri of camera image to save.
final File root = new File (Environment.getExternalStorageDirectory () + File.separator + "DCIM/Camera" + File.separator);
root.mkdirs ();
final String fname = "image_" + getRandomName () + ".jpeg";
final File sdImageMainDirectory = new File (root, fname);
outputFileUri = Uri.fromFile (sdImageMainDirectory);
// Camera.
final List<Intent> cameraIntents = new ArrayList<Intent> ();
final Intent captureIntent = new Intent (android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra (MediaStore.EXTRA_OUTPUT, Uri.fromFile (sdImageMainDirectory));
final PackageManager packageManager = getPackageManager ();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities (captureIntent, 0);
for (ResolveInfo res : listCam) {
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent (captureIntent);
intent.setComponent (new ComponentName (res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage (packageName);
intent.putExtra (MediaStore.EXTRA_OUTPUT, outputFileUri);
cameraIntents.add (intent);
}
// Filesystem.
final Intent galleryIntent = new Intent ();
galleryIntent.setType ("image/*");
galleryIntent.setAction (Intent.ACTION_GET_CONTENT);
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser (galleryIntent, "Select Source");
// Add the camera options.
chooserIntent.putExtra (Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray (new Parcelable[] {}));
startActivityForResult (chooserIntent, 1);
}
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
super.onActivityResult (requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
final boolean isCamera;
if (data == null) {
isCamera = true;
}
else {
final String action = data.getAction ();
if (action == null) {
isCamera = false;
}
else {
isCamera = action.equals (android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
Uri selectedImageUri;
if (isCamera) {
selectedImageUri = outputFileUri;
}
else {
selectedImageUri = data == null ? null : data.getData ();
}
imageView1.setImageURI (selectedImageUri);
}
}
}
public String getRandomName () {
Random r = new Random (); // just create one and keep it around
String alphabet = "abcdefghijklmnopqrstuvwxyz1234567890";
final int N = 10;
StringBuilder sb = new StringBuilder ();
for (int i = 0; i < N; i++) {
sb.append (alphabet.charAt (r.nextInt (alphabet.length ())));
}
return sb.toString ();
}
I'm trying to:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, RESULTADO_GALERIA);
.
.
.
String imgPath = data.getDataString(); // return something like "/external/images/media/13852"
BitmapFactory.decodeFile(imgPath); // allways null...
I also tried:
File bitmapFile = new File(Environment.getExternalStorageDirectory()
+ "/" + imgPath);
String aux = bitmapFile.getAbsolutePath(); // /storage/sdcard0/external/images/media/13852
BitmapFactory.decodeFile(bitmapFile.getAbsolutePath()); // NULL
An the result it's the same
The olny thing work's for me is put the path manually...
File file = new File("/storage/sdcard0/DCIM/Camera/"+"IMG_20140506_101341.jpg"); // nothing to do with the path obtained by code...
BitmapFactory.decodeFile(bitmapFile.getAbsolutePath()); // OK
How can I get the REAL path for a image of the gallery? Other ideas to resize them?
Thanks!
I have demonstrate to Both the case
1) capture Photo from camera
2) Take a photo from gallary
Try this is working like charm with me
private String selectedImagePath = "";
final private int PICK_IMAGE = 1;
final private int CAPTURE_IMAGE = 2;
public Uri setImageUri() {
// Store image in dcim
File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".png");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
}
public String getImagePath() {
return imgPath;
}
btnGallery.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, ""), PICK_IMAGE);
}
});
btnCapture.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
startActivityForResult(intent, CAPTURE_IMAGE);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_CANCELED) {
if (requestCode == PICK_IMAGE) {
selectedImagePath = getAbsolutePath(data.getData());
imgUser.setImageBitmap(decodeFile(selectedImagePath));
} else if (requestCode == CAPTURE_IMAGE) {
selectedImagePath = getImagePath();
imgUser.setImageBitmap(decodeFile(selectedImagePath));
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
public Bitmap decodeFile(String path) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 70;
// Find the correct scale value. It should be the power of 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeFile(path, o2);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
public String getAbsolutePath(Uri uri) {
String[] projection = { MediaColumns.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
i am creating an application using camera. The intent returns null value in samsung mobile. but it is perfectly working in sony mobile. i don't know whats problem in that.My code is here.
Intent cameraIntent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
private static File getOutputMediaFile(int type) {
mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
Log.i("mediaFile",""+mediaFile);
return mediaFile;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST_CODE&& resultCode == RESULT_OK) {
String[] projection = { MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(mCapturedImageURI, projection, null, null, null);
int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String capturedImageFilePath = cursor.getString(column_index_data);
Toast.makeText(this, capturedImageFilePath, Toast.LENGTH_SHORT).show();
}
File sdImageMainDirectory = new File(root, ActivityConst.ENCYIMAGE);
Uri outputFileUri = Uri.fromFile(sdImageMainDirectory);
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, CAMERA_CAPTURE);
I am following this in my app its working fine
I have demonstrate to Both the case
1) capture Photo from camera
2) Take a photo from gallary
Try this is working like charm with me
private String selectedImagePath = "";
final private int PICK_IMAGE = 1;
final private int CAPTURE_IMAGE = 2;
public Uri setImageUri() {
// Store image in dcim
File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".png");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
}
public String getImagePath() {
return imgPath;
}
btnGallery.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, ""), PICK_IMAGE);
}
});
btnCapture.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
startActivityForResult(intent, CAPTURE_IMAGE);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_CANCELED) {
if (requestCode == PICK_IMAGE) {
selectedImagePath = getAbsolutePath(data.getData());
imgUser.setImageBitmap(decodeFile(selectedImagePath));
} else if (requestCode == CAPTURE_IMAGE) {
selectedImagePath = getImagePath();
imgUser.setImageBitmap(decodeFile(selectedImagePath));
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
public Bitmap decodeFile(String path) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 70;
// Find the correct scale value. It should be the power of 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeFile(path, o2);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
public String getAbsolutePath(Uri uri) {
String[] projection = { MediaColumns.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}