我正在尝试从相机捕捉图像,它可以在横向模式下正常工作,当我拍摄照片时,它会旋转。以下是我正在使用的代码:
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inJustDecodeBounds = true;
BitmapFactory.decodeFile(largeImagePath, bounds);
Bitmap bm = BitmapFactory.decodeFile(largeImagePath, opts);
ExifInterface exif = new ExifInterface(largeImagePath);
String orientString = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
System.out.println("Orientation camera:"+orientString);
int orientation = orientString != null ? Integer.parseInt(orientString) : ExifInterface.ORIENTATION_NORMAL;
int rotationAngle = 0;
if (orientation == ExifInterface.ORIENTATION_ROTATE_90){
rotationAngle = 90;
System.out.println("In 90 degrees rotate");
}
if (orientation == ExifInterface.ORIENTATION_ROTATE_180){
rotationAngle = 180;
System.out.println("In 180 degrees rotate");
}
if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
rotationAngle = 270;
System.out.println("In 270 degrees rotate");
}
Matrix matrix = new Matrix();
System.out.println("Rotation Angle"+rotationAngle);
matrix.setRotate(rotationAngle, (float) thumbnail.getWidth() / 2, (float) thumbnail.getHeight() / 2);
bitmap = Bitmap.createBitmap(bm, 0, 0, bounds.outWidth, bounds.outHeight, matrix, true);
在调试时,控件进入:
if (orientation == ExifInterface.ORIENTATION_ROTATE_90){
rotationAngle = 90;}
阻止,但是没有旋转将图片重新设置为正确。
这是我的XML:
<ImageView
android:id="@+id/imageView1"
android:layout_width="140dp"
android:layout_height="160dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="10dp"
android:layout_marginTop="30dp"
android:src="@drawable/btn_upload" />
02-27 13:51:55.126: I/System.out(16549): Exceptionjava.lang.IllegalArgumentException: x + width must be <= bitmap.width()
答案 0 :(得分:3)
您可以按照以下方式安排代码......
Bitmap bm = BitmapFactory.decodeFile(largeImagePath, opts);
ExifInterface ei;
try {
ei = new ExifInterface(largeImagePath);
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
bitmap = rotateImage(bitmap, 90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
bitmap = rotateImage(bitmap, 180);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
bitmap = rotateImage(bitmap, 270);
break;
}
} catch (IOException e) {
e.printStackTrace();
}
编写rotateImage()
方法如下....
private Bitmap rotateImage(Bitmap source, float angle) {
Bitmap bitmap = null;
Matrix matrix = new Matrix();
matrix.postRotate(angle);
try {
bitmap = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(),
matrix, true);
} catch (OutOfMemoryError err) {
err.printStackTrace();
}
return bitmap;
}
答案 1 :(得分:2)
在bm.getWidth()
方法中使用bm.getHeight()
和bounds.outWidth
代替bounds.outHeight
和createBitmap()
。