1

Hello I am working on one android app where I need to capture the image using camera intent and set the bitmap in the imageview but here bitmap is rotated by 90 degree. I have checked many threads of stackoverflow like Photo rotate 90 degree while capture in some phones but did not work for me.

Here when I am executing this exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1); then it is returning 0 ORIENTATION_UNDEFINED and in my getImage function no condition is satisfying.

Intent cameraIntent = new Intent(
        android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
capturedPhotoName = System.currentTimeMillis() + ".png";
File photo = new File(Environment.getExternalStorageDirectory(),
        capturedPhotoName);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(cameraIntent, CAMERA_INTENT_REQUEST);

onActivityResult

Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
    bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr,
            selectedImage);
    bitmap = Util.getImage(bitmap, selectedImage.toString());
    mPictureImageView.setImageBitmap(bitmap);
} catch (Exception e) {
    Log.e("New Issue Activity", e.toString());
}

/**
 * Get the image orientation
 * 
 * @param imagePath
 * @return orietation angle
 * @throws IOException 
 */
public static Bitmap getImage(Bitmap bitmap, String path) throws IOException {
    Matrix m = new Matrix();
    ExifInterface exif = new ExifInterface(path);
    int orientation = exif
            .getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
    if ((orientation == ExifInterface.ORIENTATION_ROTATE_180)) {
        m.postRotate(180);
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                bitmap.getHeight(), m, true);
        return bitmap;
    } else if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
        m.postRotate(90);
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                bitmap.getHeight(), m, true);
        return bitmap;
    } else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
        m.postRotate(270);
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                bitmap.getHeight(), m, true);
        return bitmap;
    }
    return bitmap;
}
Community
  • 1
  • 1
N Sharma
  • 33,489
  • 95
  • 256
  • 444

3 Answers3

1

I implemented one photo take activity which you can take the photo and set the orientation of the photo. It is supported by every device I tested including Samsung galaxy series, tablets, sony xperia series, tablets.

You can check out my accepted answer about rotation of images on this topic:

Camera capture orientation on samsung devices in android

If you also need to save and use that image that you have rotated, saving and using the photo functions additional to my answer I gave above:

savePhoto function:

public void savePhoto(Bitmap bmp) {

        imageFileFolder = new File(Environment.getExternalStorageDirectory(),
                cc.getDirectoryName());
        imageFileFolder.mkdir();
        FileOutputStream out = null;
        Calendar c = Calendar.getInstance();
        String date = fromInt(c.get(Calendar.MONTH))
                + fromInt(c.get(Calendar.DAY_OF_MONTH))
                + fromInt(c.get(Calendar.YEAR))
                + fromInt(c.get(Calendar.HOUR_OF_DAY))
                + fromInt(c.get(Calendar.MINUTE))
                + fromInt(c.get(Calendar.SECOND));
        imageFileName = new File(imageFileFolder, date.toString() + ".jpg");
        try {
            out = new FileOutputStream(imageFileName);
            bmp.compress(Bitmap.CompressFormat.JPEG, 70, out);
            out.flush();
            out.close();
            scanPhoto(imageFileName.toString());
            out = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

scanPhoto function:

public void scanPhoto(final String imageFileName) {
        geniusPath = imageFileName;
        msConn = new MediaScannerConnection(MyClass.this,
                new MediaScannerConnectionClient() {
                    public void onMediaScannerConnected() {
                        msConn.scanFile(imageFileName, null);

                    }

                    @Override
                    public void onScanCompleted(String path, Uri uri) {

                        msConn.disconnect();

                    }
                });
        msConn.connect();
    }

SavePhotoTask class:

class SavePhotoTask extends AsyncTask<byte[], String, String> {
        @Override
        protected String doInBackground(byte[]... jpeg) {
            File photo = new File(Environment.getExternalStorageDirectory(),
                    "photo.jpg");
            if (photo.exists()) {
                photo.delete();
            }
            try {
                FileOutputStream fos = new FileOutputStream(photo.getPath());
                fos.write(jpeg[0]);
                fos.close();
            } catch (java.io.IOException e) {
            }
            return (null);
        }
    }
Community
  • 1
  • 1
canova
  • 3,965
  • 2
  • 22
  • 39
  • Although this bug seems to prop in Samsung devices, the OP is finding it difficult to do on a Sony device. – Skynet Apr 22 '14 at 11:23
-1

Try below code:-

                    Uri selectedImageURI = data.getData();
                    imageFile = new File(getRealPathFromURI(selectedImageURI));
                    ExifInterface exif = new ExifInterface(imageFile.toString());  
                    int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);  
                    Bitmap bitmap = Utility.getOrientationFromExif(new Utility().compressImage1(imageFile.toString(),((Activity)context)),orientation);
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG , 50 , bos);

Utility.java

public class Utility
{

    public Bitmap compressImage1(String imageUri, Activity act)
    {
        String filePath = getRealPathFromURI(imageUri, act);

        BitmapFactory.Options options = new BitmapFactory.Options();

        // by setting this field as true, the actual bitmap pixels are not
        // loaded in the memory. Just the bounds are loaded. If
        // you try the use the bitmap here, you will get null.
        options.inJustDecodeBounds = true;
        // Bitmap bmp = decodeBitmap(Uri.parse(imageUri), 612, 816, act);
        Bitmap bmp = BitmapFactory.decodeFile(filePath, options);

        // setting inSampleSize value allows to load a scaled down version of
        // the original image
        options.inSampleSize = calculateInSampleSize(options, 612, 816);

        // inJustDecodeBounds set to false to load the actual bitmap
        options.inJustDecodeBounds = false;

        // this options allow android to claim the bitmap memory if it runs low
        // on memory
        options.inPurgeable = true;
        options.inInputShareable = true;
        options.inTempStorage = new byte[16 * 1024];

            // load the bitmap from its path
        bmp = BitmapFactory.decodeFile(filePath, options);
        return bmp;
    }           


    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight)
    {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth)
        {

            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            // Calculate the largest inSampleSize value that is a power of 2 and
            // keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth)
            {
                inSampleSize *= 2;
            }
        }

        return inSampleSize;
    }



    public static Bitmap getOrientationFromExif(Bitmap bitmap, int orientation)
    {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int newWidth = 612;
        int newHeight = 816;

        // calculate the scale - in this case = 0.4f
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        Matrix matrix = new Matrix();
        switch (orientation)
        {
            case ExifInterface.ORIENTATION_NORMAL:
                return bitmap;
            case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
//              matrix.setScale(-1, 1);
                matrix.postScale(scaleWidth, scaleHeight);
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                matrix.setRotate(180);
                break;
            case ExifInterface.ORIENTATION_FLIP_VERTICAL:
                matrix.setRotate(180);
//              matrix.postScale(-1, 1);
                matrix.postScale(scaleWidth, scaleHeight);
                break;
            case ExifInterface.ORIENTATION_TRANSPOSE:
                matrix.setRotate(90);
//              matrix.postScale(-1, 1);
                matrix.postScale(scaleWidth, scaleHeight);
                break;
            case ExifInterface.ORIENTATION_ROTATE_90:
                matrix.setRotate(90);
                break;
            case ExifInterface.ORIENTATION_TRANSVERSE:
                matrix.setRotate(-90);
//              matrix.postScale(-1, 1);
                matrix.postScale(scaleWidth, scaleHeight);
                break;
            case ExifInterface.ORIENTATION_ROTATE_270:
                matrix.setRotate(-90);
                break;
            default:
                return bitmap;
        }
        try
        {
            Bitmap bmRotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
            bitmap.recycle();
            return bmRotated;
        }
        catch (OutOfMemoryError e)
        {
            e.printStackTrace();
            return null;
        }
    }

}
duggu
  • 37,851
  • 12
  • 116
  • 113
  • On this `exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);` then it is returning 0 ORIENTATION_UNDEFINED and in your code there is no such case of ORIENTATION_UNDEFINED – N Sharma Apr 22 '14 at 11:25
-1

This function worked for me, try your luck.

public static Bitmap rotateImage(Bitmap bmp, String imageUrl) {
    if (bmp != null) {
        ExifInterface ei;
        int orientation = 0;
        try {
            ei = new ExifInterface(imageUrl);
            orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            // e.printStackTrace();
        }

        int bmpWidth = bmp.getWidth();
        int bmpHeight = bmp.getHeight();
        Matrix matrix = new Matrix();
        switch (orientation) {
        case ExifInterface.ORIENTATION_ROTATE_90:
            matrix.postRotate(90);
            break;
        case ExifInterface.ORIENTATION_ROTATE_180:
            matrix.postRotate(180);
            break;
        default:
            break;
        // etc.
        }

        Bitmap resizedBitmap = Bitmap.createBitmap(bmp, 0, 0, bmpWidth,
                bmpHeight, matrix, true);
        return resizedBitmap;
    } else {
        return bmp;
    }
}
sais
  • 803
  • 6
  • 15