图像使用相机意图旋转90度

时间:2014-04-22 11:12:30

标签: android android-intent bitmap

您好我正在开发一个Android应用程序,我需要使用相机intent捕获图像并在imageview中设置位图,但此处位图旋转90度。我检查了许多stackoverflow的线程,如Photo rotate 90 degree while capture in some phones,但对我没用。

当我执行此exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);时,它返回0 ORIENTATION_UNDEFINED并且在我的getImage函数中没有条件令人满意。

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;
}

3 个答案:

答案 0 :(得分:1)

我实施了一项拍照活动,您可以拍摄照片并设置照片的方向。我测试的每台设备都支持它,包括三星galaxy系列,平板电脑,索尼xperia系列,平板电脑。

您可以查看我接受的有关此主题图片轮换的答案:

Camera capture orientation on samsung devices in android

如果您还需要保存并使用已旋转的图像,请保存并使用我上面给出的答案之外的照片功能:

savePhoto功能:

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功能:

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 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);
        }
    }

答案 1 :(得分:-1)

尝试以下代码: -

                    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;
        }
    }

}

答案 2 :(得分:-1)

这个功能对我有用,试试运气。

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;
    }
}