Android camera saving images with wrong orientation

你说的曾经没有我的故事 提交于 2019-12-04 15:38:53

Here is how I solved it (full implementation that includes saving the image). Image taken in in portrait mode will be rotated 90 degrees.

   import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.List;
    import android.app.Activity;
    import android.content.Context;
    import android.content.Intent;
    import android.content.pm.PackageManager;
    import android.content.pm.ResolveInfo;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.graphics.Matrix;
    import android.net.Uri;
    import android.os.Bundle;
    import android.os.Environment;
    import android.os.Handler;
    import android.provider.MediaStore;
    import android.telephony.TelephonyManager;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.ImageView;
    import android.widget.Toast;

    public class ImageTakeAndShow extends Activity {

        private static final int ACTION_TAKE_PHOTO = 1;

        private static final String BITMAP_STORAGE_KEY = "viewbitmap";
        private static final String IMAGEVIEW_VISIBILITY_STORAGE_KEY = "imageviewvisibility";
        //private ImageView mImageView;
        private Bitmap mImageBitmap;
        private String mCurrentPhotoPath;

        private static final String JPEG_FILE_PREFIX = "IMG_";
        private static final String JPEG_FILE_SUFFIX = ".jpg";
        TelephonyManager myPhonenumber;
        static String device_id;  
        double latitude ,longitude;
        Button Btn;
        File f;

        //save picture
        private File getAlbumDir() {
            File file = null;

            if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                file = Environment.getExternalStorageDirectory().getAbsoluteFile();
                file = new File(Environment.getExternalStorageDirectory()
                        + File.separator + "Snap/Capture_Image");
                Log.e("file", file.toString());

                if (file != null) {
                    if (! file.mkdirs()) {
                        if (! file.exists()){
                            Log.d("Camera", "failed to create directory");
                            return null;
                        }
                    }
                }
            } else {
                Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
            }

            return file;
        }

        //create file name
        private File createImageFile() throws IOException {
            // Create an image file name
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
            File albumF = getAlbumDir();
            File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX, albumF);
            return imageF;
        }

        private File setUpPhotoFile() throws IOException {
            File f = createImageFile();
            mCurrentPhotoPath = f.getAbsolutePath();
            return f;
        }

        //set picture width and height and rotate 90 degrees
        private void setPic() {
            /* Get the size of the image */
            BitmapFactory.Options bmOptions = new BitmapFactory.Options();
            bmOptions.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
            int photoW = bmOptions.outWidth/2;
            int photoH = bmOptions.outHeight/2;

             Log.e("photoW", Integer.valueOf(photoW).toString());
             Log.e("photoH", Integer.valueOf(photoH).toString());
            int scaleFactor = 1;
            bmOptions.inJustDecodeBounds = false;
            bmOptions.inSampleSize = scaleFactor;
            bmOptions.inPurgeable = true;

            try{
                Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath);
                bitmap = Bitmap.createScaledBitmap(bitmap, 800, 600, true);
                ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);

                File f = new File(mCurrentPhotoPath.toString());
                FileOutputStream fo = new FileOutputStream(f);
                fo.write(bytes.toByteArray());
                    fo.close();
                    Matrix matrix = new Matrix();
                    matrix.postRotate(90);    
                    Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, 800,640,matrix, true); 
                    FileOutputStream fos2 = new FileOutputStream(mCurrentPhotoPath.toString());
                    rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos2);
                    fos2.close();
                }catch (Exception e) {
                    e.printStackTrace();
                }catch (OutOfMemoryError o) {
                    o.printStackTrace();
            }

        }

        private void galleryAddPic() {
                Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
                f = new File(mCurrentPhotoPath);
                Uri contentUri = Uri.fromFile(f);
                mediaScanIntent.setData(contentUri);
                this.sendBroadcast(mediaScanIntent);
                Log.e("path f", f.toString());
        }

        //Camera activity
        private void dispatchTakePictureIntent(int actionCode) {
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            switch(actionCode) {
            case ACTION_TAKE_PHOTO:
                File f = null;

                try {
                    f = setUpPhotoFile();
                    mCurrentPhotoPath = f.getAbsolutePath();
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                } catch (IOException e) {
                    e.printStackTrace();
                    f = null;
                    mCurrentPhotoPath = null;
                }
                break;

            default:
                break;          
            }
            startActivityForResult(takePictureIntent, actionCode);
        }

        private void handleBigCameraPhoto() {
            if (mCurrentPhotoPath != null) {
                setPic();
                galleryAddPic();
                mCurrentPhotoPath = null;
            }
        }

        Button.OnClickListener mTakePicOnClickListener = 
            new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                dispatchTakePictureIntent(ACTION_TAKE_PHOTO);
            }
        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            myPhonenumber   = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
            device_id       =  myPhonenumber.getDeviceId();
            mImageBitmap = null;
            dispatchTakePictureIntent(ACTION_TAKE_PHOTO);
        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            switch (requestCode) {
            case ACTION_TAKE_PHOTO: {
                if (resultCode == RESULT_OK) {
                    handleBigCameraPhoto();

                    final Intent intent = new Intent(getApplicationContext(), Image_Priview.class);
                    intent.putExtra("image parth",  f.toString());
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);  
                    finish(); 


                      new Handler().postDelayed(new Runnable() {
                            public void run() {

                            }
                        }, 1000);


                }else if (resultCode == RESULT_CANCELED){
                     File file = new File(mCurrentPhotoPath);
                     file.delete();
                     finish();  

                }
                break;
            }
            }
        }

        // Some lifecycle callbacks so that the image can survive orientation change
        @Override
        protected void onSaveInstanceState(Bundle outState) {
            outState.putParcelable(BITMAP_STORAGE_KEY, mImageBitmap);
            outState.putBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY, (mImageBitmap != null) );
            super.onSaveInstanceState(outState);
        }

        @Override
        protected void onRestoreInstanceState(Bundle savedInstanceState) {
            super.onRestoreInstanceState(savedInstanceState);
            mImageBitmap = savedInstanceState.getParcelable(BITMAP_STORAGE_KEY);
        }

        public static boolean isIntentAvailable(Context context, String action) {
            final PackageManager packageManager = context.getPackageManager();
            final Intent intent = new Intent(action);
            List<ResolveInfo> list =
                packageManager.queryIntentActivities(intent,
                        PackageManager.MATCH_DEFAULT_ONLY);
            return list.size() > 0;
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!