2

in my Android app I capture the photo in portrait mode but when photo is saved is convert in landscape mode but I want to save photo in portrait mode

CaptureActivity.java

public class CaptureActivity extends Activity 
{   
     // Activity request codes
    private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
    public static final int MEDIA_TYPE_IMAGE = 1;

    // imageview for display captured image
    ImageView imagecapture;

    // file url to store image/video
    public Uri fileUri; 

    // Classes For Database
    private     SQLiteDatabase  mSQLiteDatabase = null;
    private     DB_Helper       mDB_Helper = null;

    public static ContextWrapper contextWrapper;


    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.capturephoto);  

        imagecapture=(ImageView)findViewById(R.id.imagecapture);
        contextWrapper = new ContextWrapper(getApplicationContext());

       // Checking camera availability
        if(!isDeviceSupportCamera()) 
        {
            Toast.makeText(getApplicationContext(),"Sorry! Your device doesn't support camera", Toast.LENGTH_LONG).show();
            // will close the app if the device does't have camera
            finish();
        }
        else
        {
            captureImage();
        }

    }

     /* Opening DB */
    private void Open_Database() 
    {
        mDB_Helper = new DB_Helper(this);
        mSQLiteDatabase = mDB_Helper.getWritableDatabase();
    }

    /* Closing DB */
    private void Close_Database() 
    {
        if (mSQLiteDatabase != null && mDB_Helper != null) {
            mSQLiteDatabase.close();
            mDB_Helper.close();
        }
    }

     /**
     * Checking device has camera hardware or not
     * */
    private boolean isDeviceSupportCamera() 
    {
        if(getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) 
        {
            // this device has a camera
            return true;
        } 
        else 
        {
            // no camera on this device
            return false;
        }
    }

    /**
     * Capturing Camera Image will lauch camera app requrest image capture
     */
    private void captureImage()
    {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT,fileUri);
          // start the image capture Intent
        startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
    }

    /**
     * Here we store the file url as it will be null after returning from camera
     * app
     */

    @Override
    protected void onSaveInstanceState(Bundle outState) 
    {
        super.onSaveInstanceState(outState);

        // save file url in bundle as it will be null on scren orientation
        // changes
        outState.putParcelable("file_uri", fileUri);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) 
    {
        super.onRestoreInstanceState(savedInstanceState);

        // get the file url
        fileUri = savedInstanceState.getParcelable("file_uri");
    }

    /**
     * Receiving activity result method will be called after closing the camera
     * 
     * */

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    {
        // if the result is capturing Image
        if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) 
        {
            if (resultCode == RESULT_OK) 
            {
                // successfully captured the image
                // display it in image view
                previewCapturedImage();
            }
            else if (resultCode == RESULT_CANCELED) 
            {
                // user cancelled Image capture
                Toast.makeText(getApplicationContext(),
                        "User cancelled image capture", Toast.LENGTH_SHORT)
                        .show();
            } 
            else 
            {
                // failed to capture image
                Toast.makeText(getApplicationContext(),"Sorry! Failed to capture image", Toast.LENGTH_SHORT).show();
            }
        }
    }    



    /**
     * Display image from a path to ImageView
     */
    private void previewCapturedImage() 
    {
        try 
        {         

            // for open database
            Open_Database();

            Bitmap bitmap;
            try {
                bitmap = getImage(fileUri.getPath(),getApplicationContext() );
                 imagecapture.setImageBitmap(bitmap);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date myDate = new Date();
            String realdatetime = dateformat.format(myDate);
            Log.e("Current Date","------>"+realdatetime);

            mDB_Helper.Insert_MYPHOTOS_Table(mSQLiteDatabase,"title",realdatetime, "description",fileUri.getPath());

            // for close database
            Close_Database();

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

    }


    public Bitmap getImage(String path,Context con) throws IOException
    {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        int srcWidth = options.outWidth;
        int srcHeight = options.outHeight;
        int[] newWH =  new int[2];
        newWH[0] = srcWidth/2;
        newWH[1] = (newWH[0]*srcHeight)/srcWidth;

        int inSampleSize = 1;
        while(srcWidth / 2 >= newWH[0]){
            srcWidth /= 2;
            srcHeight /= 2;
            inSampleSize *= 2;
        }

         options.inJustDecodeBounds = false;
        options.inDither = false;
        options.inSampleSize = inSampleSize;
        options.inScaled = false;
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        Bitmap sampledSrcBitmap = BitmapFactory.decodeFile(path,options);
        ExifInterface exif = new ExifInterface(path);
        String s=exif.getAttribute(ExifInterface.TAG_ORIENTATION);
        System.out.println("Orientation>>>>>>>>>>>>>>>>>>>>"+s);
        Matrix matrix = new Matrix();
        float rotation = rotationForImage(con, Uri.fromFile(new File(path)));
        if (rotation != 0f) {
            matrix.preRotate(rotation);
        }

        Bitmap pqr=Bitmap.createBitmap(
                sampledSrcBitmap, 0, 0, sampledSrcBitmap.getWidth(), sampledSrcBitmap.getHeight(), matrix, true);


        return pqr;
    }   


    public  float rotationForImage(Context context, Uri uri) {
        if (uri.getScheme().equals("content")) {
            String[] projection = { Images.ImageColumns.ORIENTATION };
            Cursor c = context.getContentResolver().query(
                    uri, projection, null, null, null);
            if (c.moveToFirst()) {
                return c.getInt(0);
            }
        } else if (uri.getScheme().equals("file")) {
            try {
                ExifInterface exif = new ExifInterface(uri.getPath());
                int rotation = (int)exifOrientationToDegrees(
                        exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                                ExifInterface.ORIENTATION_NORMAL));
                return rotation;
            } catch (IOException e) {
                e.printStackTrace();
            }catch (Exception e) {
                e.printStackTrace();
             }

        }
        return 0f;
    }

    private static float exifOrientationToDegrees(int exifOrientation) {
        if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) {
            return 90;
        } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {
            return 180;
        } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) {
            return 270;
        }
        return 0;
    }

    /**
     * ------------ Helper Methods ----------------------
     * */

    /**
     * Creating file uri to store image/video
     */
    public Uri getOutputMediaFileUri(int type) 
    {
        return Uri.fromFile(getOutputMediaFile(type));
    }

    /**
     * returning image / video
     */
    private static File getOutputMediaFile(int type) 
    {

           File mediaFile = null;

           Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
           if(isSDPresent)
           {
               File directory= new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/Mymemoryphotos");

                if(!directory.exists())
                {   
                    Log.e("Create External Directory","------>");
                    directory.mkdirs();
                }

                 // Create a media file name
                String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",Locale.getDefault()).format(new Date());


                if (type == MEDIA_TYPE_IMAGE) 
                {
                    mediaFile = new File(directory.getPath() + File.separator + "IMG_" + timeStamp + ".JPEG");
                }
                else 
                {

                    return null;

                }
           }
           else
           {

               File directory = contextWrapper.getDir("Mymemoryphotos", Context.MODE_PRIVATE);

                if(!directory.exists())
                {   
                    Log.e("Create Internal Directory","------>");
                    directory.mkdirs();

                }

                // Create a media file name
                String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",Locale.getDefault()).format(new Date());              

                if (type == MEDIA_TYPE_IMAGE) 
                {
                    mediaFile = new File(directory.getPath() + File.separator + "IMG_" + timeStamp + ".JPEG");
                }
                else 
                {

                    return null;

                }
           }

        return mediaFile;
    }

}

I want result like this when photo saved in sdcard

enter image description here

My current result when capture image in portrait mode but photo auto convert to landscape mode

enter image description here

Cœur
  • 37,241
  • 25
  • 195
  • 267
Mahesh
  • 1,559
  • 6
  • 27
  • 57

1 Answers1

0

Use ExifInterface to read photo EXIF tags & rotate bitmap when you show it. You may check this for some sample code, however it needs to be edited & cleaned a bit

Sam
  • 1,652
  • 17
  • 25
  • hey when i show image in imageview is already done with potrait but i want to rotate image when i was saved in sdcard it is possible – Mahesh Feb 22 '14 at 08:12
  • I don't uderstand you. Please try to construct sentences better – Sam Feb 22 '14 at 09:17
  • see first i capture the image in portrait mode than i saved that image in sdcard but this image is saved in landscape mode not in portrait mode image is automatically rotate in landscape mode – Mahesh Feb 22 '14 at 09:27
  • Well, I don't yet understand you. Also, READ my answer at last. – Sam Feb 22 '14 at 11:22