解决三星拍照横屏问题

三星手机的问题 :竖着拍照 ,保存的照片确是横着的,

下面上代码,

  /**
     *  file:  照片文件
     *  quality:新生成的照片压缩质量
     */
    @Throws(FileNotFoundException::class)
    fun compressImageAndSave(file: File, quality: Int): String {
        var bm = BitmapFactory.decodeFile(file.absolutePath)
        val degree = readPictureDegree(file.absolutePath)
        if (degree != 0) {//旋转照片角度
            bm = rotateBitmap(bm, degree)
        }

        val out = FileOutputStream(file.absolutePath)
        bm!!.compress(Bitmap.CompressFormat.JPEG, quality, out)
        return file.path
    }

    /**
     * 旋转图片
     */
    fun rotateBitmap(bitmap: Bitmap?, degress: Int): Bitmap? {
        var bitmap = bitmap
        if (bitmap != null) {
            val m = Matrix()
            m.postRotate(degress.toFloat())
            bitmap = Bitmap.createBitmap(
                bitmap, 0, 0, bitmap.width,
                bitmap.height, m, true
            )
            return bitmap
        }
        return bitmap
    }

    /**
     * 读取照片的旋转角度
     */
    fun readPictureDegree(path: String): Int {
        var degree = 0
        try {
            val exifInterface = ExifInterface(path)
            val orientation = exifInterface.getAttributeInt(
                ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_NORMAL
            )
            when (orientation) {
                ExifInterface.ORIENTATION_ROTATE_90 -> degree = 90
                ExifInterface.ORIENTATION_ROTATE_180 -> degree = 180
                ExifInterface.ORIENTATION_ROTATE_270 -> degree = 270
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }

        return degree
    }

用的话 只要一行compressImageAndSave(mTmpFile,100);

这里拿到拍完照的照片定义为mTmpFile,然后根据照片旋转的角度,  我断点 orientation 得到是这个

public static final int ORIENTATION_ROTATE_90 = 6;  // rotate 90 cw to right it

根据实际拍到的图片 是逆时针转了90度

所以 我们只要顺时针再转90就能解决这个问题,对于英文的这个注释我也不是很懂

下面是别人给我的方法:

仅供参考

public static String compressImageAndSave(String imageDir, String filePath, String fileName, int q) throws FileNotFoundException {

        Bitmap bm = getSmallBitmap(filePath);
        int degree = readPictureDegree(filePath);
        if (degree != 0) {//旋转照片角度
            bm = rotateBitmap(bm, degree);
        }

        File outputFile = new File(imageDir, fileName);
        FileOutputStream out = new FileOutputStream(outputFile);
        bm.compress(Bitmap.CompressFormat.JPEG, q, out);
        return outputFile.getPath();
    }

猜你喜欢

转载自blog.csdn.net/xiexiaotian11/article/details/89927624
今日推荐