At the moment I am selecting an image from gallery and the whole path is shown example (/storage/emulated.0/DCIM/Camera/123.jpg) in the textview whereas I only want the name of the image to be shown example 123.jpg.
public String getRealPathFromURI(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
BitmapFactory.Options options;
if (resultCode == RESULT_OK && requestCode == PICTURE_SELECTED) {
try {
options = new BitmapFactory.Options();
options.inSampleSize = 4;
Uri selectedImage = data.getData();
String s= getRealPathFromURI(selectedImage);
imageName.append(s);
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePath, null, null, null);
cursor.moveToFirst();
String mImagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
InputStream stream = getContentResolver().openInputStream(selectedImage);
Bitmap yourSelectedImage = BitmapFactory.decodeStream(stream, null, options);
stream.close();
//---orientation---
try {
int rotate = 0;
try {
ExifInterface exif = new ExifInterface(
mImagePath);
dateTaken.append(exif.getAttribute(ExifInterface.TAG_DATETIME));
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
}
} catch (Exception e) {
e.printStackTrace();
}
Matrix matrix = new Matrix();
matrix.postRotate(rotate);
yourSelectedImage = Bitmap.createBitmap(yourSelectedImage , 0, 0, yourSelectedImage.getWidth(), yourSelectedImage.getHeight(), matrix, true);
}
catch (Exception e) {}
//---end of orientation---
imgButton.setScaleType(ImageView.ScaleType.FIT_CENTER);
imgButton.setImageBitmap(yourSelectedImage);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Could not open file.", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getApplicationContext(), "Image was not selected", Toast.LENGTH_LONG).show();
}
Log.i(TAG, "onActivityResult - Portal");
}
Followed this link Get filepath and filename of selected gallery image in Android
You need to perform a String operation.follwoing code will help you out.
String path=":/storage/sdcard0/DCIM/Camera/1414240995236.jpg";
String filename=path.substring(path.lastIndexOf("/")+1);
possible duplicate of :
How to get file name from file path in android
Related
I'm trying to load an image from gallery in a ImageView. This code work correctly on Huawei p10, but don't work correctly on Samsung s5 and other devices. When i load the image the orientation is not correctly.
I'm using this function to load from gallery but the orientation is always 0.
public void loadPostImage(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE1);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE1) {
selectedImageUri = data.getData();
if (null != selectedImageUri) {
flag=true;
path = selectedImageUri.getPath();
int orientation = getOrientation(getApplicationContext(), selectedImageUri);
Log.e("image path", path + "");
image_post.setImageURI(selectedImageUri);
}
}
}
}
private static int getOrientation(Context context, Uri photoUri) {
Cursor cursor = context.getContentResolver().query(photoUri,
new String[]{MediaStore.Images.ImageColumns.ORIENTATION}, null, null, null);
if (cursor.getCount() != 1) {
cursor.close();
return -1;
}
cursor.moveToFirst();
int orientation = cursor.getInt(0);
cursor.close();
cursor = null;
return orientation;
}
I tried also with EXIF. But nothing is changed.
public void controlRotate(Uri photoUri) throws IOException {
ExifInterface exif = new ExifInterface(photoUri.getPath());
int exifRotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED);
switch (exifRotation) {
case ExifInterface.ORIENTATION_ROTATE_90: {
float photoRotation = 90.0f;
break;
}
case ExifInterface.ORIENTATION_ROTATE_180: {
float photoRotation = 180.0f;
break;
}
case ExifInterface.ORIENTATION_ROTATE_270: {
float photoRotation = 270.0f;
break;
}
}
}
I resolved the problem using this snippet
public void orientation(Uri selectedImageUri){
Uri uri = selectedImageUri; // the URI you've received from the other app
InputStream in = null;
try {
in = getContentResolver().openInputStream(uri);
ExifInterface exifInterface = new ExifInterface(in);
int rotation = 0;
int orientation = exifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotation = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotation = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotation = 270;
break;
}
// Now you can extract any Exif tag you want
// Assuming the image is a JPEG or supported raw format
} catch (IOException e) {
// Handle any errors
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ignored) {}
}
}
}
I have been trying to save images to Firebase Storage but I noticed that almost all pictures saved from Gallery/Google Drive get rotated.(usually by 90 degrees)
Reading through older posts I realized that this is a common issue and I tried solving it by trying either solution from this post , or from this one , this one and I could go on.
After roughly 8 hours I finally decided to ask here. Is there a better and easier implementation to stop the images from getting rotated?
My last (and unsuccessful, obviously) implementation using ExifInterface (which returns all the time 0) is this one:
Selecting picture
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
OnActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContext().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
int rotateImageAngle = getPhotoOrientation(getContext(), selectedImage, filePath);
try {
bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), selectedImage);
// Log.d(TAG, String.valueOf(bitmap));
addPictureButton.setText("Done");
} catch (IOException e) {
e.printStackTrace();
}
if( bitmap != null)
{
RotateBitmap(bitmap , rotateImageAngle);
}
}
Helper methods
public int getPhotoOrientation(Context context, Uri imageUri, String imagePath){
int rotate = 0;
try {
context.getContentResolver().notifyChange(imageUri, null);
File imageFile = new File(imagePath);
ExifInterface exif = new ExifInterface(imageFile.getAbsolutePath());
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
}
Log.i("RotateImage", "Exif orientation: " + orientation);
Log.i("RotateImage", "Rotate value: " + rotate);
} catch (Exception e) {
e.printStackTrace();
}
return rotate;
}
public static Bitmap RotateBitmap(Bitmap source, int angle)
{
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
}
Note: If needed I will add the code that uploads images to Firebase
I have come to a solution thanks to this post.
I am going to post below a modified working version of the code for anybody that has this issue.
Fire up picture selection from gallery
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(intent, PICK_IMAGE_REQUEST);
OnActivityResult checking original roatation of the selected picture
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && requestCode == PICK_IMAGE_REQUEST) {
// Get selected gallery image
Uri selectedPicture = data.getData();
// Get and resize profile image
String[] filePathColumn = {MediaStore.Images.Media.DATA};
// TRY getactvity() as well if not work
Cursor cursor = getContext().getContentResolver().query(selectedPicture, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
loadedBitmap = BitmapFactory.decodeFile(picturePath);
ExifInterface exif = null;
try {
File pictureFile = new File(picturePath);
exif = new ExifInterface(pictureFile.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
int orientation = ExifInterface.ORIENTATION_NORMAL;
if (exif != null)
orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
loadedBitmap = rotateBitmap(loadedBitmap, 90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
loadedBitmap = rotateBitmap(loadedBitmap, 180);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
loadedBitmap = rotateBitmap(loadedBitmap, 270);
break;
}
imageView.setImageBitmap(loadedBitmap);
}
}
RotateBitmap method
public static Bitmap rotateBitmap(Bitmap bitmap, int degrees) {
Matrix matrix = new Matrix();
matrix.postRotate(degrees);
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
I am using the following code to get the orientation of the selected image so that if it was taken vertically, when selected from gallery it would not be shown horizontally.
The error is occuring in the
File imageFile = new File(selectedImage.toString()); in the parameter selectedImage.toString()) since when I changed the initial int rotate=90 and chose a vertical image the result was good.
Am I passing the parameter to the File correct?
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
BitmapFactory.Options options;
if (resultCode == RESULT_OK && requestCode == PICTURE_SELECTED) {
try {
options = new BitmapFactory.Options();
options.inSampleSize = 4;
Uri selectedImage = data.getData();
InputStream stream = getContentResolver().openInputStream(selectedImage);
Bitmap yourSelectedImage = BitmapFactory.decodeStream(stream, null, options);
stream.close();
//orientation
try {
int rotate = 0;
try {
File imageFile = new File(selectedImage.toString());
ExifInterface exif = new ExifInterface(
imageFile.getAbsolutePath());
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
}
} catch (Exception e) {
e.printStackTrace();
}
Matrix matrix = new Matrix();
matrix.postRotate(rotate);
yourSelectedImage = Bitmap.createBitmap(yourSelectedImage , 0, 0, yourSelectedImage.getWidth(), yourSelectedImage.getHeight(), matrix, true); }
catch (Exception e) {}
//end of orientation
imgButton.setScaleType(ImageView.ScaleType.FIT_CENTER);
imgButton.setImageBitmap(yourSelectedImage);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Could not open file.", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getApplicationContext(), "Image was not selected", Toast.LENGTH_LONG).show();
}
super.onActivityResult(requestCode, resultCode, data);
}
Modify your method like this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
BitmapFactory.Options options;
if (resultCode == RESULT_OK && requestCode == PICTURE_SELECTED) {
try {
options = new BitmapFactory.Options();
options.inSampleSize = 4;
Uri selectedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePath, null, null, null);
cursor.moveToFirst();
String mImagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
InputStream stream = getContentResolver().openInputStream(selectedImage);
Bitmap yourSelectedImage = BitmapFactory.decodeStream(stream, null, options);
stream.close();
//orientation
try {
int rotate = 0;
try {
ExifInterface exif = new ExifInterface(
mImagePath);
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
}
} catch (Exception e) {
e.printStackTrace();
}
Matrix matrix = new Matrix();
matrix.postRotate(rotate);
yourSelectedImage = Bitmap.createBitmap(yourSelectedImage , 0, 0, yourSelectedImage.getWidth(), yourSelectedImage.getHeight(), matrix, true); }
catch (Exception e) {}
//end of orientation
imgButton.setScaleType(ImageView.ScaleType.FIT_CENTER);
imgButton.setImageBitmap(yourSelectedImage);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Could not open file.", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getApplicationContext(), "Image was not selected", Toast.LENGTH_LONG).show();
}
}
for image handling compile picasso is best library using it you can easily handle images using it you can load image from cache also and increase performance of your app so try to avoid doing lots of code and add following line in your build gradle and then use picasso in your code.
compile 'com.squareup.picasso:picasso:2.5.0'
Hi am capturing an image through camera intent it works good but my problem is that am not getting preview of that image
my requirement is very simple, after clicking of photo through camera it must ask me to SAVE or DISCARD this image if i press SAVE then it get save into sd card thats it...
here is my code
private void openCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
capturedFile = new File(Environment.getExternalStorageDirectory(),
"tmp_nookster_profilepic"
+ String.valueOf(System.currentTimeMillis()) + ".jpg");
mImageCaptureUri = Uri.fromFile(capturedFile);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
mImageCaptureUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA_NO_CROP);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case PICK_FROM_CAMERA_NO_CROP: {
iu.SaveCapturedImage(BitmapFactory.decodeFile(capturedFile
.getAbsolutePath()));
try {
if (capturedFile.exists())
capturedFile.delete();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
break;
here "iu" is object of ImageUtility class and "SaveCapturedImage" is method to store that captured image in SdCard
You can get a preview of the captured File as this:
Bitmap getPreview(File image) {
final int THUMBNAIL_SIZE = 72;
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inJustDecodeBounds = true;
BitmapFactory.decodeFile(image.getPath(), bounds);
if ((bounds.outWidth == -1) || (bounds.outHeight == -1))
return null;
int originalSize = (bounds.outHeight > bounds.outWidth) ? bounds.outHeight
: bounds.outWidth;
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = originalSize / THUMBNAIL_SIZE;
return BitmapFactory.decodeFile(image.getPath(), opts);
}
then you can show the Bitmap in an ImageView and present the user with Save/Delete buttons.
You have to remove line from your code.
if (resultCode != RESULT_OK)
return;
Use following code :
if (resultCode == RESULT_OK)
{
try
{
Bitmap bitmap=null;
String imageId = convertImageUriToFile(imageUri,AddRecipes.this);
bitmap = BitmapFactory.decodeFile(imageId);
}}
public static String convertImageUriToFile (Uri contentUri, Activity activity)
{
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader cursorLoader = new CursorLoader(activity.getApplicationContext(),contentUri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
I'm trying to save an image loaded from the gallery to the phone memory(local path). Can anyone guide me into this?
This is how I get the image from the gallery.
ImageView profilePicture;
private Uri imageUri;
String picturePath;
#Override
public void onCreate(Bundle savedInstanceState)
{
profilePicture = (ImageView) findViewById(R.id.profile_picture);
profilePicture.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
switch (arg1.getAction()) {
case MotionEvent.ACTION_DOWN: {
break;
}
case MotionEvent.ACTION_UP:{
uploadImage();
break;
}
}
return true;
}
});
}
uploadImage()
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, 1);
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 0:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
profilePicture.setImageBitmap(bitmap);
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
.show();
Log.e("Camera", e.toString());
}
}
case 1:
if (resultCode == Activity.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]);
picturePath = cursor.getString(columnIndex);
cursor.close();
profilePicture.setBackgroundColor(Color.TRANSPARENT);
profilePicture.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
}
*Note: Case 0 is for image capturing using phones camera.
I can display it on my imageview but I need to store this in the phone's memory so everytime I will open the app, I will be able to load the previous uploaded image to the image view. Then if the user wants to upload again. The file previously saved will just be overwritten. I don't want to result to storing images as blob using sqlite since I will be uploading just one image for my whole app. I want to store it in a local file path like myappname/images/image.png. Any ideas? Thanks!
You can store an image in the application cache directory such as:
try {
String destFolder = getCacheDir().getAbsolutePath()+ "/images/";
if (!new File(destFolder).exists()) {
new File(destFolder).mkdirs();
}
FileOutputStream out = new FileOutputStream(destFolder + "profile.png");
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
And read back the file into the Bitamp:
String fname = "profile.png";
Bitmap profile = BitmapFactory.decodeFile(getCacheDir().getAbsolutePath()+ "/images/" + fname);