我有以下代码,该代码从给定的图像图像文件路径创建位图:
private fun loadBitmap(filePath: String?): Bitmap {
val options = BitmapFactory.Options()
options.inPreferredConfig = Bitmap.Config.ARGB_8888
return BitmapFactory.decodeFile(filePath, options)
}
在我的片段类的onCreateView()方法中调用:
bitmapOfImage = loadBitmap(args.getString(FILE_PATH))
用bitmapOfImage
以某种方式修改了位图RenderScript
,然后将其加载到ImageView
中:
// do some modification on the bitmap
// ...
// copy modified pixels to 'bitmapIn'
allocationOut.copyTo(bitmapIn)
// load it into the imageview specified by its ID 'modifiedImage'
binding.modifiedImage.setImageBitmap(bitmapIn)
因此,我用CameraX
拍摄图像,并且文件路径被传递到上述图像处理片段的loadBitmap()
方法。但是,尽管我以人像模式拍摄图像,但它以横向版本显示。
这里有一个小图像,当我拍摄图像时看起来像:
您可以看到图像似乎向右旋转。为什么呢这是默认情况下发生的吗?我该如何解决?为了完整起见,这是我的XML布局,用于显示捕获的照片:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/imagecontainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ImageModificationFragment">
<ImageView
android:id="@+id/modified_image"
android:layout_width="0dp"
android:layout_height="0dp"
android:adjustViewBounds="true"
android:scaleType="fitCenter"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:contentDescription="@string/shows_filtered_image" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
要获得所需的方向,请用ExifInterface检查方向并在必要时旋转位图。
下面的示例代码:
Matrix matrix = new Matrix();
Bitmap bitmap = 'your bitmap';
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] imageBytes = stream.toByteArray();
ExifInterface exifInterface = new ExifInterface(new ByteArrayInputStream(imageBytes));
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.postRotate(90);
bitmap = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(),
matrix, true);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.postRotate(180);
bitmap = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(),
matrix, true);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
matrix.postRotate(270);
bitmap = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(),
matrix, true);
break;
default:
break;
}