Android

Android Bitmap轉File File轉Bitmap 壓縮&旋轉

Android Bitmap轉File File轉Bitmap 壓縮&旋轉

  1. 將Bitmap轉為File
  2. 路徑取得File
  3. 用質量壓縮圖片(2M)
  4. 將圖片角度旋轉為正

1.將Bitmap轉為File

val bitmap = BitmapFactory.decodeResource(resources, R.drawable.girl)
val file = File(externalCacheDir, "girl.jpg")
val ops = FileOutputStream(file)
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, ops)

2.路徑取得File

val file = File(externalCacheDir, "girl.jpg")
compressFile(file)

3.用質量壓縮圖片(2M)

private fun compressFile(file: File) {
    //2M
    val twoMB = 1024 * 1024 * 2
    var quality = 100
    if (file.exists()) {
        while (file.length() > twoMB) {
            quality -= 5
            val bitmap = BitmapFactory.decodeFile(file.absolutePath)
            val matrix = Matrix()
            //把角度轉正
            matrix.setRotate(readPictureDegree(file.absolutePath))
            val createBitmap =
                Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
            val out = FileOutputStream(File(file.absolutePath))
            createBitmap.compress(Bitmap.CompressFormat.JPEG, quality, out)
            out.flush()
            out.close()
        }
    }
}

4.將圖片角度旋轉為正

private fun readPictureDegree(path: String): Float {
    var degree = 0f
    val exifInterface = ExifInterface(path)
    val orientation = exifInterface.getAttributeInt(
        ExifInterface.TAG_ORIENTATION,
        ExifInterface.ORIENTATION_NORMAL
    )
    when (orientation) {
        ExifInterface.ORIENTATION_ROTATE_90 -> degree = 90f
        ExifInterface.ORIENTATION_ROTATE_180 -> degree = 180f
        ExifInterface.ORIENTATION_ROTATE_270 -> degree = 270f
    }
    return degree
}

發表迴響