微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Android 相机 Exif 没有方向数据但图像已旋转

如何解决Android 相机 Exif 没有方向数据但图像已旋转

我正在使用以下辅助类来处理相机图像的采样和旋转。

object CaptureImageHelper {

/**
 * This method is responsible for solving the rotation issue if exist. Also scale the images to
 * 1024x1024 resolution
 *
 * @param context       The current context
 * @param selectedImage The Image URI
 * @return Bitmap image results
 * @throws IOException
 */
@Throws(IOException::class)
fun handleSamplingAndRotationBitmap(
    context: Context,selectedImage: Uri?,isFrontCamera: Boolean
): Bitmap? {
    val MAX_HEIGHT = 1024
    val MAX_WIDTH = 1024

    // First decode with inJustDecodeBounds=true to check dimensions
    val options = BitmapFactory.Options()
    options.inJustDecodeBounds = true
    var imagestream: InputStream = context.getContentResolver().openInputStream(selectedImage!!)!!
    BitmapFactory.decodeStream(imagestream,null,options)
    imagestream.close()

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options,MAX_WIDTH,MAX_HEIGHT)

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false
    imagestream = context.getContentResolver().openInputStream(selectedImage!!)!!
    var img = BitmapFactory.decodeStream(imagestream,options)
    img = rotateImageIfrequired(img!!,selectedImage,isFrontCamera)
    return img
}

/**
 * Calculate an inSampleSize for use in a [BitmapFactory.Options] object when decoding
 * bitmaps using the decode* methods from [BitmapFactory]. This implementation calculates
 * the closest inSampleSize that will result in the final decoded bitmap having a width and
 * height equal to or larger than the requested width and height. This implementation does not
 * ensure a power of 2 is returned for inSampleSize which can be faster when decoding but
 * results in a larger bitmap which isn't as useful for caching purposes.
 *
 * @param options   An options object with out* params already populated (run through a decode*
 * method with inJustDecodeBounds==true
 * @param reqWidth  The requested width of the resulting bitmap
 * @param reqHeight The requested height of the resulting bitmap
 * @return The value to be used for inSampleSize
 */
private fun calculateInSampleSize(
    options: BitmapFactory.Options,reqWidth: Int,reqHeight: Int
): Int {
    // Raw height and width of image
    val height = options.outHeight
    val width = options.outWidth
    var inSampleSize = 1
    if (height > reqHeight || width > reqWidth) {

        // Calculate ratios of height and width to requested height and width
        val heightRatio =
            Math.round(height.toFloat() / reqHeight.toFloat())
        val widthRatio =
            Math.round(width.toFloat() / reqWidth.toFloat())

        // Choose the smallest ratio as inSampleSize value,this will guarantee a final image
        // with both dimensions larger than or equal to the requested height and width.
        inSampleSize = if (heightRatio < widthRatio) heightRatio else widthRatio

        // This offers some additional logic in case the image has a strange
        // aspect ratio. For example,a panorama may have a much larger
        // width than height. In these cases the total pixels might still
        // end up being too large to fit comfortably in memory,so we should
        // be more aggressive with sample down the image (=larger inSampleSize).
        val totalPixels = width * height.toFloat()

        // Anything more than 2x the requested pixels we'll sample down further
        val totalReqPixelsCap = reqWidth * reqHeight * 2.toFloat()
        while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
            inSampleSize++
        }
    }
    return inSampleSize
}

/**
 * Rotate an image if required.
 *
 * @param img           The image bitmap
 * @param selectedImage Image URI
 * @return The resulted Bitmap after manipulation
 */
@Throws(IOException::class)
private fun rotateImageIfrequired(
    img: Bitmap,selectedImage: Uri,isFrontCamera: Boolean
): Bitmap? {
    val ei = ExifInterface(selectedImage.path!!)
    val orientation: Int =
        ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,ExifInterface.ORIENTATION_norMAL)
    return when (orientation) {
        ExifInterface.ORIENTATION_ROTATE_90 -> rotateImage(img,90,isFrontCamera)
        ExifInterface.ORIENTATION_ROTATE_180 -> rotateImage(img,180,isFrontCamera)
        ExifInterface.ORIENTATION_ROTATE_270 -> rotateImage(img,270,isFrontCamera)
        else -> img
    }
}

private fun rotateImage(
    img: Bitmap,degree: Int,isFrontCamera: Boolean
): Bitmap? {
    val matrix = Matrix()
    if(isFrontCamera) {
        val matrixMirrorY = Matrix()
        val mirrorY = floatArrayOf(-1f,0f,1f,1f)
        matrixMirrorY.setValues(mirrorY)
        matrix.postConcat(matrixMirrorY)
        matrix.preRotate(270f)
    } else {
        matrix.postRotate(degree.toFloat())
    }
    val rotatedImg =
        Bitmap.createBitmap(img,img.width,img.height,matrix,true)
    img.recycle()
    return rotatedImg
}
}

调用助手类

val bitmap = CaptureImageHelper.handleSamplingAndRotationBitmap(requireContext(),Uri.fromFile(cameraimage!!),false)

我遇到的问题是随机的。大多数情况下,如果我在声明下方获得旋转图像

ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,ExifInterface.ORIENTATION_norMAL)

返回 ExifInterface.ORIENTATION_ROTATE_90 很好,代码正确旋转该图像。但有时图像被旋转但它 Exif getAttributeInt 返回 ExifInterface.ORIENTATION_norMAL。我相信这意味着没有针对此图像的 Exif/Orientation 数据,它返回认值。

退出获取属性方法

    public int getAttributeInt(@NonNull String tag,int defaultValue) {
    if (tag == null) {
        throw new NullPointerException("tag shouldn't be null");
    }
    ExifAttribute exifAttribute = getExifAttribute(tag);
    if (exifAttribute == null) {
        return defaultValue;
    }

    try {
        return exifAttribute.getIntValue(mExifByteOrder);
    } catch (NumberFormatException e) {
        return defaultValue;
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。