How to know if picture is landscape or portrait? - android

I have pictures in my Gallery that are both landscape or portrait. The show up correctly in the Gallery application. When I use an intent to select the picture from the gallery I get a URI back. But before I display the picture how do I know if the picture is portrait or landscape?
My application selects pictures using an Intent like this:
private OnClickListener btnChooseFromLibraryListener = new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, REQ_CODE_PICK_IMAGE);
}
};
Here is how I get the intent back:
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case REQ_CODE_PICK_IMAGE:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.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 filePath = cursor.getString(columnIndex);
cursor.close();
SetPicture(filePath);
}
}
}
private void SetPicture(String filePath) {
Bitmap bm = BitmapFactory.decodeFile(filePath);
Log.d("TW", "Picture Path:" + filePath);
String size = String.format("Width:%d Height:%d", bm.getWidth(), bm.getHeight());
Log.d("TW", size);
ivPicture.setImageBitmap(bm);
ui.setLastPicture(filePath);
}

Use this inside onActivityResult()
Uri selectedImage = imageReturnedIntent.getData();
String[] orientationColumn = {MediaStore.Images.Media.ORIENTATION};
Cursor cur = managedQuery(selectedImage, orientationColumn, null, null, null);
int orientation = -1;
if (cur != null && cur.moveToFirst()) {
orientation = cur.getInt(cur.getColumnIndex(orientationColumn[0]));
}
And use Matrix object to rotate your images
Matrix matrix = new Matrix();
matrix.postRotate(orientation);

There's a MediaStore.Images.Media.ORIENTATION field used by the content provider.
The code would need to be slightly modified by including the field to tell you what orientation the image is at which is expressed in degrees, 0, 90, 180, 270.
String[] filePathColumn = {
MediaStore.Images.Media.DATA,
MediaStore.Images.Media.ORIENTATION
};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn,
null,
null,
null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
int orientationIndex = cursor.getColumnIndex(filePathPathColumn[1]);
String filePath = cursor.getString(columnIndex);
String degreesOrientation = cursor.getString(orientationIndex);
cursor.close();
// Now degreesOrientation will tell you exactly the rotation, as in
int nDegrees = Integer.parse(degreesOrientation);
// Check nDegrees - for example: if (nDegrees == 0 || nDegrees == 180) portrait.

After the above "Answers" I wrote the following method. Hopefully this will help someone else.
private int GetRotateAngle(Uri imageUri) {
String[] columns = {MediaStore.Images.Media.DATA, MediaStore.Images.Media.ORIENTATION};
Cursor cursor = getContentResolver().query(imageUri, columns, null, null, null);
if (cursor == null) { return 0; }
cursor.moveToFirst();
int orientationColumnIndex = cursor.getColumnIndex(columns[1]);
int orientation = cursor.getInt(orientationColumnIndex);
cursor.close();
return orientation;
}

Related

How to solve issue of path of any photo in gallery for kitkat and further versions?

I used this onActivityResult method to fetch photo from Gallery or camera
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == 0) {
finish();
photoFile = null;
theftimage.setImageResource(R.drawable.camera);
}
if (requestCode == REQUEST_TAKE_PHOTO) {
theftimage.setVisibility(View.VISIBLE);
setPic();
}
if (requestCode == SELECT_PICTURE) {
// Get the url from data
if(resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
if (null != selectedImageUri) {
// Get the path from the Uri
String path; //= getPathFromURI(selectedImageUri);
path = ImageFilePath.getPath(getApplicationContext(), selectedImageUri);
String filename=path.substring(path.lastIndexOf("/")+1);
etFileName.setText(filename);
Log.i(TAG, "Image Path : " + path);
// Set the image in ImageView
theftimage.setImageBitmap(BitmapFactory.decodeFile(path));
}
}
}
}
and its method for fetching path
public String getPathFromURI(Uri contentUri) {
String res = null;
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return contentUri.getPath();
}
error is
02-28 11:00:18.488: E/HAL(24576): hw_get_module_by_class: module name gralloc
02-28 11:00:18.488: E/HAL(24576): hw_get_module_by_class: module name gralloc
its giving me error of path in kitkat and further versions. Can you solve this? Help will be appriciated.
You do not need a path if all that you want is putting the selected file in a ImageView.
One statement will do for all Android versions:
theftimage.setImageBitmap(BitmapFactory.decodeStream(
getContentResolver().openInputStream(data.getData())));
Please try the following code:
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
String imgDecodableString;
if(cursor==null) {
imgDecodableString= selectedImage.getPath();
}
else {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
}
}
imgDecodableString will contain the final path of the image and you can set the picture in your ImageView as :
theftimage.setImageBitmap(BitmapFactory.decodeFile(imgDecodableString));

Getting "Caused by: java.lang.NullPointerException: uri" when trying to set image after capturing it

I have 2 option to set an image, either by choosing it from gallery or by capturing it.
When user chooses image from gallery, it return a clank ImageView and when the user try to set image after capturing it, the app crashes giving following error: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.abc.xyz/com.abc.xyz.Activity}: java.lang.NullPointerException: uri
Here's how I'm launching the chooser:
protected DialogInterface.OnClickListener mDialogListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int position) {
switch (position) {
case 0: // Take picture
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePhotoIntent, TAKE_PHOTO_REQUEST);
break;
case 1: // Choose picture
Intent choosePhotoIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
choosePhotoIntent.setType("image/*");
startActivityForResult(choosePhotoIntent, PICK_PHOTO_REQUEST);
break;
}
}
};
Here's how I'm setting the image to the ImageView:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == PICK_PHOTO_REQUEST || requestCode == TAKE_PHOTO_REQUEST) {
if (data == null) {
// display an error
return;
}
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
// error on the line below
Cursor cursor = this.getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
//
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Picasso.with(this)
.load(picturePath)
.into(hPic);
hPicTag.setVisibility(View.INVISIBLE);
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(getBaseContext(), "Something went wrong!", Toast.LENGTH_LONG).show();
}
}
Please let me know what is wrong here.
Sorry for bad formatting of the question. I'm still a beginner here.
The way to obtain path is different is certain Android versions. I use the following Util class for this purpose.
public class RealPathUtil {
#SuppressLint("NewApi")
public static String getRealPathFromURI_API20(Context context, Uri uri){
String filePath = "";
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = { MediaStore.Images.Media.DATA };
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{ id }, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
}
public static String getRealPathFromURI_API11to19(Context context, Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
String result = null;
if(Looper.myLooper() == null) {
Looper.prepare();
}
CursorLoader cursorLoader = new CursorLoader(
context,
contentUri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
if(cursor != null){
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
result = cursor.getString(column_index);
} else {
result = contentUri.getPath();
}
return result;
}
public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri){
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);
}
}
Now based on the device's OS version call appropriate methods as:
if (Build.VERSION.SDK_INT < 11) {
RealPathUtil.getRealPathFromURI_BelowAPI11(...);
} else if(Build.VERSION.SDK_INT >= 11 && <= 19) {
RealPathUtil.getRealPathFromURI_API11to19(...);
} else if(Build.VERSION.SDK_INT > 19){
RealPathUtil.getRealPathFromURI_API20(...);
}
Try like this.
This will surely help you...Tested....
final String[] items = new String[]{"Camera", "Gallery"};
new AlertDialog.Builder(getActivity()).setTitle("Select Picture")
.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Camera")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals("Gallery")) {
if (Build.VERSION.SDK_INT <= 19) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
} else if (Build.VERSION.SDK_INT > 19) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
}
}
}
}).show();
}
// get result after selecting image from Gallery
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == getActivity().RESULT_OK && null != data) {
Uri selectedImageUri = data.getData();
String selectedImagePath = getRealPathFromURIForGallery(selectedImageUri);
decodeFile(selectedImagePath);
} else if (requestCode == REQUEST_CAMERA && resultCode == getActivity().RESULT_OK && null != data) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
profileImage.setImageBitmap(photo);
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
Uri tempUri = getImageUri(getActivity().getApplicationContext(), photo);
// CALL THIS METHOD TO GET THE ACTUAL PATH
File finalFile = new File(getRealPathFromURI(tempUri));
decodeFile(finalFile.toString());
}
}
public String getRealPathFromURIForGallery(Uri uri) {
if (uri == null) {
return null;
}
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
return uri.getPath();
}
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, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getActivity().getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
// decode image
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);
Security connection = new Security(context);
Boolean isInternetPresent = connection.isConnectingToInternet(); // true or false
if (isInternetPresent) {
// submit usr information to server
//first upload file
updateUserProfileImage();
Log.i("IMAGEPATH", "" + imagePath);
}
profileImageView.setImageBitmap(bitmap);
}

Why I am unable to set ImageBitmap to RelativeLayout here?

I'm trying to select a background image from gallery and set it as Activity background. But the problem is here when I set RelativeLayout instead of ImageView, it gives me error on setImageBitmap, what;s the reason here? Here's my code: I referred to this tutorial : http://viralpatel.net/blogs/pick-image-from-galary-android-app/ Thanks in advance!
#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.background);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
That is because RelativeLayout doesn't have a method called setImageBitmap.
Referring to this link, you can use this to set it to your relative layout:
File f = new File(getRealPathFromURI(path));
Drawable d = Drawable.createFromPath(f.getAbsolutePath());
mRelativeLayout.setBackground(d);
private String getRealPathFromURI(Uri contentURI) {
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
return contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
}
You can't do setImageBitmap on a RelativeLayout. I think what you want to do is setBackground which takes in a Drawable as parameter.

Image resolution or size issue gives 'Force Close' error

I have 2 imageView to import images from gallery and set on these imageViews. I basically do this by:
String mPicPath1, mPicPath2;
protected void onCreate(Bundle icicle) {
mPicPath1 = null;
mPicPath2 = null;
}
#Override
protected void onActivityResult(int requestCode, int resultcode, Intent data){
super.onActivityResult(requestCode, resultcode, data);
switch(requestCode){
case 1:
if (data != null && resultcode == RESULT_OK)
{
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]);
mPicPath1 = cursor.getString(columnIndex);
cursor.close();
logoview.setBackgroundResource(0);
logoview.setImageBitmap(BitmapFactory.decodeFile(mPicPath1));
}
break;
case 2:
if (data != null && resultcode == RESULT_OK)
{
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
cursor.moveToFirst();
mPicPath2 = cursor.getString(columnIndex);
cursor.close();
qrcodeview.setBackgroundResource(0);
qrcodeview.setImageBitmap(BitmapFactory.decodeFile(mPicPath2));
}
break;
}
and i use a button onClickListener to start intent and go to SecondActivity:
save=(Button)findViewById(R.id.save);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(NewCard.this, Template.class);
if (!TextUtils.isEmpty(mPicPath1)) {
intent.putExtra("picture_path1", PicPath1);
}
if (!TextUtils.isEmpty(mPicPath2)) {
intent.putExtra("picture_path2", PicPath2);
}
startActivity(intent);
}
});
And my SecondActivity to set images on 2 different imageViews:
String pre_img_path1= getIntent().getStringExtra("picture_path1");
ImageView crdlogoframe = (ImageView) findViewById(R.id.crdlogoframe);
crdlogoframe.setImageBitmap(BitmapFactory.decodeFile(pre_img_path1));
String pre_img_path2= getIntent().getStringExtra("picture_path2");
ImageView crdqrframe = (ImageView) findViewById(R.id.crdqrframe);
crdqrframe.setImageBitmap(BitmapFactory.decodeFile(pre_img_path2));
So my problem is about the file size or resolution of the images. If i take 2 high resolution images from gallery (taken by standard camera: 1992kb, 3264x2448) and i click my save (save.onClickListener) button, i receive Force Close error. If i take small size images there is no problem(74kb, 800x600) i can proceed SecondActivity and see images are set. How i can solve this issue. Should i use a syntax to resize the images when i pick or set. The formats are both .Jpeg. Thank you very much.
i do not have the rep to comment yet so .... but as Simon said your images are to large 31MB need to try and keep things under about 16MB so you will have to re-size them before you can display them
Instead of
BitmapFactory.decodeFile(mPicPath2)
You need to use something like
BitmapFactory.decodeFile(mPicPath2, options)
Where options is an instance of BitmapFactory.Options with an inSampleSize set to something like 4 that will scale down the image as it is loaded.

Not able to pick photo from gallery?

I am able to open the gallery and getting the path of gallery as=
content://media/external/images/media/2
but not able to decode in imageview
this is my code
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b=(Button) findViewById(R.id.Button01);
b.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// in onCreate or any event where your want the user to
// select a file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,IMAGE_PICK);
}
});
}
//UPDATED
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == IMAGE_PICK) {
Uri selectedImageUri = data.getData();
//OI FILE Manager
filemanagerstring = selectedImageUri.getPath();
//MEDIA GALLERY
selectedImagePath = getPath(selectedImageUri);
if(selectedImagePath!=null)
{
path = selectedImageUri.toString();
m1.setPath(path);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Bitmap yourSelectedImage = BitmapFactory.decodeFile(path, options);
ImageButton img2=(ImageButton)findViewById(R.id.widget27);
img2.setImageBitmap(yourSelectedImage);
Toast.makeText(getBaseContext(), path, 1000).show();
}
}
}
}
public String getPath(Uri uri) {
String [] proj={MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(uri,
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
Please help thanks in advance
This piece of code should be put in your onActivityResult. It gives you the way to decode file path from fetched image URI:
Uri selectedImageUri = data.getData();
String[] projection = { MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(selectedImageUri, projection, null, null, null);
int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
selectedImagePath = cursor.getString(column_index_data);
Bitmap galleryImage = BitmapFactory.decodeFile(selectedImagePath);
We need to do following changes/fixes in our earlier onActivityResult()'s gallery picker code to run seamlessly on Kitkat and on all other earlier versions as well.
Uri selectedImgFileUri = data.getData();
if (selectedImgFileUri == null ) {
// user has not selected any photo
}
try {
InputStream input = mActivity.getContentResolver().openInputStream(selectedImgFileUri);
mSelectedPhotoBmp = BitmapFactory.decodeStream(input);
} catch (Throwable tr) {
// show message to try again
}

Categories

Resources