安卓相册导入

3

我正在使用画廊选择器从图库中选择图像。相机拍摄的竖屏照片在画廊中显示为直立状态。但是当我导入这些照片时,它们会旋转(变成横屏)。只有画廊显示这张图片是正立的。如何解决这个问题?我希望所有照片都按照它们的实际方向显示。

private void addImageFromGallery() {

    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"),
            GALLERY_CODE);

}

相册应用在拍照时知道手机的确切方向,因此会旋转图片。但我却没有得到这个效果。 - Zacharias Manuel
这个教程可以帮助你:http://startandroiddevelopment.blogspot.in/2013/10/importing-image-from-gallery.html - user834900
2个回答

11

得到了答案。方向是保存在图像的EXIF格式中的。我们需要读取每个图像数据的方向标签。

public static float rotationForImage(Context context, Uri uri) {
        if (uri.getScheme().equals("content")) {
        String[] projection = { Images.ImageColumns.ORIENTATION };
        Cursor c = context.getContentResolver().query(
                uri, projection, null, null, null);
        if (c.moveToFirst()) {
            return c.getInt(0);
        }
    } else if (uri.getScheme().equals("file")) {
        try {
            ExifInterface exif = new ExifInterface(uri.getPath());
            int rotation = (int)exifOrientationToDegrees(
                    exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                            ExifInterface.ORIENTATION_NORMAL));
            return rotation;
        } catch (IOException e) {
            Log.e(TAG, "Error checking exif", e);
        }
    }
        return 0f;
    }

    private static float exifOrientationToDegrees(int exifOrientation) {
    if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) {
        return 90;
    } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {
        return 180;
    } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) {
        return 270;
    }
    return 0;
}
}

旋转值可用于校正照片的方向,操作如下:

Matrix matrix = new Matrix();
float rotation = PhotoTaker.rotationForImage(context, uri);
if (rotation != 0f) {
      matrix.preRotate(rotation);
 }

Bitmap resizedBitmap = Bitmap.createBitmap(
 sourceBitmap, 0, 0, width, height, matrix, true);

很好... Bitmap resizedBitmap = Bitmap.createBitmap(sourceBitmap, 0, 0, sourceBitmap.getWidth(), sourceBitmap.getHeight(), matrix, true); - Underdog
为什么rotationForImage返回一个浮点数?使用整数不足以满足要求吗? - Braden Steffaniak

0

在将其设置为ImageView时,检查图像的宽度是否大于高度,如果需要,则将其旋转90度


这是不可能的,因为我们获取的所有图像都以640X480的比例。 - Zacharias Manuel
1
已经得到答案了...每张图片都保存有一个方向标签。请查看此链接http://mobisocial.stanford.edu/news/2011/08/rotating-images-in-android/。 - Zacharias Manuel
请翻译以下有关编程的内容,从英语到中文。请仅返回翻译文本:发布您的答案。它将对他人有用 - Seshu Vinay

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接