【问题标题】:Image rotate 90 degree using camera intent使用相机意图将图像旋转 90 度
【发布时间】:2014-04-22 11:12:29
【问题描述】:

您好,我正在开发一款 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;
}

【问题讨论】:

  • 你在什么设备上测试?某些设备存在错误,您需要处理它。
  • 在 Sony 上进行测试,我试图解决这个问题,但对我不起作用

标签: android android-intent bitmap


【解决方案1】:

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

您可以查看我接受的关于此主题的图像旋转的答案:

Camera capture orientation on samsung devices in android

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

保存照片功能:

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

【讨论】:

  • 虽然这个错误似乎存在于三星设备中,但 OP 发现在索尼设备上很难做到。
【解决方案2】:

试试下面的代码:-

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

}

【讨论】:

  • 在这个 exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1); 上然后它返回 0 ORIENTATION_UNDEFINED 并且在你的代码中没有 ORIENTATION_UNDEFINED 的这种情况
【解决方案3】:

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

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

【讨论】:

  • 对我不起作用,似乎与我发布的代码相同
猜你喜欢
  • 1970-01-01
  • 2013-10-30
  • 2013-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多