当我将媒体库中的图像加载到位图中时,一切正常,除了垂直握住手机时用相机拍摄的图片被旋转,以便我始终获得水平图片,即使它在库中显示为垂直。为什么会这样?我怎样才能正确加载它?
发布于 2010-09-06 06:03:38
你看过图片的EXIF数据了吗?它可能知道拍摄照片时相机的方向。
发布于 2010-11-05 20:51:26
举个例子..。
首先,您需要创建一个ExifInterface:
ExifInterface exif = new ExifInterface(filename);
然后,您可以获取图像的方向:
orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
方向值的含义如下:http://sylvana.net/jpegcrop/exif_orientation.html
因此,最重要的值是3、6和8。例如,如果方向是ExifInterface.ORIENTATION_ROTATE_90
(即6),则可以像这样旋转图像:
Matrix matrix = new Matrix();
matrix.postRotate(90);
rotatedBitmap = Bitmap.createBitmap(sourceBitmap, 0, 0, sourceBitmap.getWidth(), sourceBitmap.getHeight(), matrix, true);
不过,这只是一个简单的例子。我相信还有其他方法可以执行实际的旋转。但你也可以在StackOverflow上找到这些。
发布于 2012-01-19 01:11:43
这是一个完整的解决方案(可以在Facebook SDK的Hackbook示例中找到)。它的优点是不需要访问文件本身。如果你正在从内容解析器加载图片(例如,如果你的应用程序正在响应分享照片的意图),这是非常有用的。
public static int getOrientation(Context context, Uri photoUri) {
/* it's on the external media. */
Cursor cursor = context.getContentResolver().query(photoUri,
new String[] { MediaStore.Images.ImageColumns.ORIENTATION }, null, null, null);
if (cursor.getCount() != 1) {
return -1;
}
cursor.moveToFirst();
return cursor.getInt(0);
}
然后你可以得到一个旋转后的位图,如下所示。这段代码还将图像缩小(不幸的是)为MAX_IMAGE_DIMENSION。否则,您可能会耗尽内存。
public static Bitmap getCorrectlyOrientedImage(Context context, Uri photoUri) throws IOException {
InputStream is = context.getContentResolver().openInputStream(photoUri);
BitmapFactory.Options dbo = new BitmapFactory.Options();
dbo.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, dbo);
is.close();
int rotatedWidth, rotatedHeight;
int orientation = getOrientation(context, photoUri);
if (orientation == 90 || orientation == 270) {
rotatedWidth = dbo.outHeight;
rotatedHeight = dbo.outWidth;
} else {
rotatedWidth = dbo.outWidth;
rotatedHeight = dbo.outHeight;
}
Bitmap srcBitmap;
is = context.getContentResolver().openInputStream(photoUri);
if (rotatedWidth > MAX_IMAGE_DIMENSION || rotatedHeight > MAX_IMAGE_DIMENSION) {
float widthRatio = ((float) rotatedWidth) / ((float) MAX_IMAGE_DIMENSION);
float heightRatio = ((float) rotatedHeight) / ((float) MAX_IMAGE_DIMENSION);
float maxRatio = Math.max(widthRatio, heightRatio);
// Create the bitmap from file
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = (int) maxRatio;
srcBitmap = BitmapFactory.decodeStream(is, null, options);
} else {
srcBitmap = BitmapFactory.decodeStream(is);
}
is.close();
/*
* if the orientation is not 0 (or -1, which means we don't know), we
* have to do a rotation.
*/
if (orientation > 0) {
Matrix matrix = new Matrix();
matrix.postRotate(orientation);
srcBitmap = Bitmap.createBitmap(srcBitmap, 0, 0, srcBitmap.getWidth(),
srcBitmap.getHeight(), matrix, true);
}
return srcBitmap;
}
https://stackoverflow.com/questions/3647993
复制相似问题