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

Android 使用相机意图将图像旋转90度,android,android-intent,bitmap,Android,Android Intent,Bitmap,您好,我正在开发一个android应用程序,我需要使用摄像头intent捕捉图像,并在imageview中设置位图,但这里位图旋转了90度。我已经检查了stackoverflow的许多线程,但没有为我工作 Uri selectedImageURI = data.getData(); imageFile = new File(getRealPathFromURI(selectedImageURI));

您好,我正在开发一个android应用程序,我需要使用摄像头
intent
捕捉图像,并在
imageview
中设置位图,但这里位图旋转了90度。我已经检查了stackoverflow的许多线程,但没有为我工作

                    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);
在这里,当我执行这个
exif.getAttributeInt(ExifInterface.TAG_方向,1)时
然后返回0
ORIENTATION\u UNDEFINED
,在my
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);
                    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);
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;
}
                    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);

请尝试以下代码:-

                    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

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

}

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

                    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);
您可以在此主题上查看我关于图像旋转的公认答案:

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

                    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);
如果您还需要保存并使用已旋转的图像,请保存并使用我在上面给出的答案之外的照片功能:

                    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);
保存照片功能:

                    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);
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();
        }
    }
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();
    }
扫描照片功能:

                    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);
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();
        }
    }
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类:

                    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);
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);
        }
    }
class SavePhotoTask扩展了AsyncTask{
@凌驾
受保护的字符串doInBackground(字节[]…jpeg){
File photo=新文件(Environment.getExternalStorageDirectory(),
“photo.jpg”);
if(photo.exists()){
photo.delete();
}
试一试{
FileOutputStream fos=新的FileOutputStream(photo.getPath());
fos.write(jpeg[0]);
fos.close();
}捕获(java.io.ioe异常){
}
返回(空);
}
}

这个功能对我很有用,试试你的运气吧

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

你在测试什么设备?在某些设备上有一个bug,你需要处理它。在Sony上测试时,我尝试过处理这个bug,但对Mealth不起作用。虽然这个bug似乎存在于三星设备上,但OP发现在Sony设备上很难做到。在这个
exif.getAttributeInt(ExifInterface.TAG\u-ORIENTATION,1)
然后它返回0 ORIENTATION\u UNDEFINED,并且在您的代码中没有这样的ORIENTATION\u UNDEFINED情况对我不起作用,它似乎与我发布的代码相同