如何解决Android Bitmap.compress 旋转图像,我需要在写入文件之前将其恢复到正常方向
我使用 Bitmap.compress 写入文件,导致图像方向错误。我尝试使用 EXIF 和许多不同的方法,但它似乎不起作用,因为我必须将其写入文件,并且在这样做时丢失了方向。当我从相机/(或从图库中选择拍摄的照片)及其高度> 宽度拍摄照片时,会发生这种情况。图像从直立变为 -90 度。问题是我无法对压缩做任何事情,因此文件以错误的方向保存。我不知何故需要将正确定向的图像保存到 tempFile
最好是适用于 API 21+ 的东西
@Throws(IOException::class)
fun getCorrectlyOrientedImage( photoUri: Uri?): Bitmap? {
var `is` = context.contentResolver.openInputStream(photoUri!!)
val dbo = BitmapFactory.Options()
dbo.inJustDecodeBounds = true
BitmapFactory.decodeStream(`is`,null,dbo)
`is`!!.close()
val rotatedWidth: Int
val rotatedHeight: Int
val orientation = getorientation(context,photoUri)
if (orientation == 90 || orientation == 270) {
rotatedWidth = dbo.outHeight
rotatedHeight = dbo.outWidth
} else {
rotatedWidth = dbo.outWidth
rotatedHeight = dbo.outHeight
}
var srcBitmap: Bitmap?
`is` = context.contentResolver.openInputStream(photoUri)
if (rotatedWidth > MAX_IMAGE_DIMENSION || rotatedHeight > MAX_IMAGE_DIMENSION) {
val widthRatio = rotatedWidth.toFloat() / MAX_IMAGE_DIMENSION.toFloat()
val heightRatio = rotatedHeight.toFloat() / MAX_IMAGE_DIMENSION.toFloat()
val maxRatio = max(widthRatio,heightRatio)
// Create the bitmap from file
val options = BitmapFactory.Options()
options.inSampleSize = maxRatio.toInt()
srcBitmap = BitmapFactory.decodeStream(`is`,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) {
val matrix = Matrix()
matrix.postRotate(orientation.toFloat())
srcBitmap = Bitmap.createBitmap(
srcBitmap!!,srcBitmap.width,srcBitmap.height,matrix,true
)
}
return srcBitmap
}
private fun getorientation(context: Context,photoUri: Uri?): Int {
/* it's on the external media. */
val cursor: Cursor? = context.contentResolver.query(
photoUri!!,arrayOf(MediaStore.Images.ImageColumns.ORIENTATION),null
)
if (cursor == null){
cursor?.close()
return -1
}
if (cursor.count != 1) {
cursor.close()
return -1
}
cursor.movetoFirst()
val orientation = cursor.getInt(0)
cursor.close()
return orientation
}
这是我如何使用它
val imageFile = if (!needsResizing) {
createTempFileFromUri(uri = imageFileUri)
} else {
val bt = getCorrectlyOrientedImage(imageFileUri)
val tempFile = File(context.filesDir.toString() + "tempfile")
bt!!.compress(
Bitmap.CompressFormat.PNG,100,tempFile.outputStream()
)
bt.recycle()
tempFile //set the imageFile to be equal to tempFile
}
如果图像不需要调整大小,一切都很好,如果它太大,那么我需要调整它的大小并将其写入文件。
这就是我需要文件的原因
val reqFile: RequestBody =
imageFile.asRequestBody("multipart/form-data".toMediaTypeOrNull())
val image = MultipartBody.Part.createFormData("image",imageFile.name,reqFile)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。