2

I am having a little problem with my android project I hope I will find a fix from you guys.

I am getting an image from Phone gallery or take the pic from the front or rare camera and setting it in an ImageView. Everything is working fine that I can get the image from the gallery and can take the pic from the camera and set it in the image view.

Problem:

The problem I am facing is that the orientation of the image is not what I want. When I Capture a picture from Front camera of my mobile the image is shown Right to left not from top to Bottom. Please see the following image:

Image Taken from the Front camera and it is showing like this in the Image View

And when I capture an image in Portrait (from rare camera) it is shown as Left to right in the ImageView not from Top to bottom.

Image Taken in Portrait mode from the rare camera and it is showing like this

And when I capture the image in Landscape mode it is shown normal in the ImageView i-e From Top to Bottom.

landscape this is the landscape mode image output..

I don't know how I fix it.. so what i am missing or what i should do to make all the images in the ImageView in Top to Bottom view.

Here are my XML and Java Files:

XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/imgProfilePic"
    android:layout_above="@+id/btnGetPic"
    />
<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/btnGetPic"
    android:layout_alignParentBottom="true"
    android:text="Get pictures from Gallery or Camera"/>

</RelativeLayout>

Java File :

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.FileNotFoundException;
import java.io.InputStream;

public class MainActivity extends AppCompatActivity {

Button btnGetPic;
ImageView imgProfilePic;
private static int REQUEST_GALLERY = 1;
private static int REQUEST_CAMERA = 2;
RoundTheImage roundedImage;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnGetPic = (Button) findViewById(R.id.btnGetPic);
    imgProfilePic = (ImageView) findViewById(R.id.imgProfilePic);

    btnGetPic.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            selectImage();
        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if (requestCode == REQUEST_CAMERA) {
            Bundle bundle = new Bundle();
            bundle = data.getExtras();
            Bitmap bmp;
            bmp = (Bitmap) bundle.get("data");
            Bitmap resized = Bitmap.createScaledBitmap(bmp, 1000, 1000, true);
            roundedImage = new RoundTheImage(resized);
            imgProfilePic.setImageDrawable(roundedImage);
        } else if (requestCode == REQUEST_GALLERY && null != data) {


            try {
                InputStream inputStream = getContentResolver().openInputStream(data.getData());
                Bitmap bmp;
                bmp = BitmapFactory.decodeStream(inputStream);

                Bitmap resized = Bitmap.createScaledBitmap(bmp, 1000, 1000, true);
                roundedImage = new RoundTheImage(resized);
                imgProfilePic.setImageDrawable(roundedImage);

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
}

private void selectImage() {
    final CharSequence[] items = {"Take Photo from Camera", "Choose from Library", "Cancel"};
    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    builder.setTitle("Add Photo!");
    builder.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            if (items[item].equals("Take Photo from Camera")) {

                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (intent.resolveActivity(getPackageManager()) != null) {
                    startActivityForResult(intent,REQUEST_CAMERA); // 1 as REQUEST_CAMERA
                }
            } else if (items[item].equals("Choose from Library"))  {

                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent,"Select Picture"), REQUEST_GALLERY);


            } else if (items[item].equals("Cancel"))                {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}

}

And I use this Class to round the edges of the images (I get this one from one of SO answers)

import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;

public class RoundTheImage extends Drawable {
private final Bitmap mBitmap;
private final Paint mPaint;
private final RectF mRectF;
private final int mBitmapWidth;
private final int mBitmapHeight;

public RoundTheImage(Bitmap bitmap) {
    mBitmap = bitmap;
    mRectF = new RectF();
    mPaint = new Paint();
    mPaint.setAntiAlias(true);
    mPaint.setDither(true);
    final BitmapShader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
    mPaint.setShader(shader);

    mBitmapWidth = mBitmap.getWidth();
    mBitmapHeight = mBitmap.getHeight();
}

@Override
public void draw(Canvas canvas) {
    canvas.drawOval(mRectF, mPaint);
}

@Override
protected void onBoundsChange(Rect bounds) {
    super.onBoundsChange(bounds);
    mRectF.set(bounds);
}

@Override
public void setAlpha(int alpha) {
    if (mPaint.getAlpha() != alpha) {
        mPaint.setAlpha(alpha);
        invalidateSelf();
    }
}

@Override
public void setColorFilter(ColorFilter cf) {
    mPaint.setColorFilter(cf);
}

@Override
public int getOpacity() {
    return PixelFormat.TRANSLUCENT;
}

@Override
public int getIntrinsicWidth() {
    return mBitmapWidth;
}

@Override
public int getIntrinsicHeight() {
    return mBitmapHeight;
}

public void setAntiAlias(boolean aa) {
    mPaint.setAntiAlias(aa);
    invalidateSelf();
}

@Override
public void setFilterBitmap(boolean filter) {
    mPaint.setFilterBitmap(filter);
    invalidateSelf();
}

@Override
public void setDither(boolean dither) {
    mPaint.setDither(dither);
    invalidateSelf();
}

public Bitmap getBitmap() {
    return mBitmap;
}

}
Rahul Tiwari
  • 6,851
  • 3
  • 49
  • 78
Hashoo
  • 47
  • 7

2 Answers2

1

How to set Android camera orientation properly?

Have a look at that, it should answer your question. Essentially you need to tell the app what orientation the camera is in based on the phone sensor and that should allow you to capture in the correct orientation. Hope it helps!

Community
  • 1
  • 1
hipkiss
  • 197
  • 2
  • 19
  • 1
    Thank you for pointing me toward right direction. I spent couple of hours and now i figured it out how to set the orientation. – Hashoo Oct 20 '15 at 15:51
1

Thanks to hipkiss for pointing me toward right direction.

Please note: This is not the best solution out there and it may not be well optimised and it may not work with every device.

For newcomers, like me, here is what my final code looked like. So it may help someone some day :)

First do this in your button's click event or in alert dialog etc

 Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
 startActivityForResult(i, REQUEST_GALLERY);

declare REQUEST_GALLERY as

 private static int REQUEST_GALLERY = 1;

And now in your onActivityResult Do something like this:

try {

                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                // Get the cursor
                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                // Move to first row
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                imgPath = cursor.getString(columnIndex);
                cursor.close();

                int rotation = getCameraPhotoOrientation(MainActivity.this,selectedImage,imgPath);

                Matrix matrix = new Matrix();
                matrix.postRotate(rotation);

                Bitmap original = BitmapFactory.decodeFile(imgPath);
                Bitmap myFinalImg = Bitmap.createBitmap(original, 0, 0, original.getWidth(), original.getHeight(), matrix, true);

                ImageView imgView = (ImageView) findViewById(R.id.imgProfilePic);
                // Set the Image in ImageView after decoding the String
                imgView.setImageBitmap(myFinalImg);

 } catch (Exception e) {
                Toast.makeText(this, "Unable to load the image", Toast.LENGTH_LONG).show();
                 }

And this function will return the rotation ( that is how much rotation should be done)

 public static int getCameraPhotoOrientation(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_UNDEFINED);

        switch (orientation) {
            case ExifInterface.ORIENTATION_NORMAL:
                rotate = 0;
                break;
            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();
    }
    return rotate;
}

@Pros out there please fix/improve this answer so it may help other and let me know how i can improve it too :)

Edit:

Don't forget to add the permission in AndroidManifest file:

   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Hashoo
  • 47
  • 7
  • OMG!!!!!!!!! I can't believe you're a genius! I'm searching for a solution 2 days, e nothing, but now, with your answer, it's perfect for me! thank you!!! <3 <3 S2 S2 <3 – João Armando Oct 15 '17 at 20:17