lmw
2023-05-12 f67802a41f9e01444d1115f34ecc6e1beb05fc3b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
package cn.sinata.xldutils.utils
 
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.graphics.Point
import android.media.ExifInterface
import android.os.Build
import android.view.WindowManager
import cn.sinata.xldutils.xldUtils
import java.io.*
import java.math.BigDecimal
 
/**
 *
 */
object BitmapUtils {
 
    data class FileInfo(val path:String){
        var width:Int=0
        var height:Int=0
    }
 
    fun compressImageFileWithSize(filePath:String):FileInfo{
        var fos: FileOutputStream? = null
        var tempBitmap: Bitmap? = null
        val path = xldUtils.PICDIR + filePath.hashCode() + ".jpg"
        val fileInfo = FileInfo(path)
        try {
            val options = BitmapFactory.Options()
            options.inJustDecodeBounds = true
            BitmapFactory.decodeFile(filePath, options)
            var scale = 1f
            val min = Math.min(options.outWidth, options.outHeight)
            val max = Math.max(options.outWidth, options.outHeight)
            if (min >= 800) {
                scale = max / 800f
            } else if (max >= 1200) {
                scale = max / 1200f
            }
            val sampleSize = BigDecimal(scale.toDouble()).setScale(0, BigDecimal.ROUND_HALF_UP).toInt()
            options.inPreferredConfig = Bitmap.Config.RGB_565
            options.inJustDecodeBounds = false
            options.inSampleSize = sampleSize
            options.inPurgeable = true
            options.inInputShareable = true
            tempBitmap = BitmapFactory.decodeFile(filePath,
                    options)
            val width = options.outWidth
            val height = options.outHeight
            fileInfo.width = width
            fileInfo.height = height
 
            val degree = readPictureDegree(filePath)
            tempBitmap = adjustPhotoRotation(tempBitmap, degree)
            val baos = ByteArrayOutputStream()
            tempBitmap.compress(Bitmap.CompressFormat.JPEG, 70, baos)
            val file = File(xldUtils.PICDIR)
            if (!file.exists()) {
                file.mkdirs()
            }
            fos = FileOutputStream(path)
            fos.write(baos.toByteArray())
 
        } catch (e: Exception) {
            e.printStackTrace()
        } catch (e: OutOfMemoryError) {
            java.lang.System.gc()
            e.printStackTrace()
        } finally {
            if (fos != null) {
                try {
                    fos.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
 
            }
            if (tempBitmap != null) {
                tempBitmap.recycle()
            }
        }
        return fileInfo
    }
    fun compressImageFile(file: File):File = compressImageFile(file.absolutePath)
    fun compressImageFile(filePath: String): File {
        val info = compressImageFileWithSize(filePath)
        return File(info.path)
    }
 
    fun decodeBitmapFromPath(context: Context,path:String):Bitmap?{
        val maxSize = calculateMaxBitmapSize(context)
        return decodeBitmapFromPath(path,maxSize[0],maxSize[1])
    }
 
    fun decodeBitmapFromPath(filePath: String, maxWidth: Int, maxHeight: Int): Bitmap? {
        var inputStream: InputStream? = null
        var bitmap: Bitmap? = null
        try {
            val file = File(filePath)
            val sampleSize = calculateBitmapSampleSize(file, maxHeight, maxWidth)
            inputStream = FileInputStream(file)
            val option = BitmapFactory.Options()
            option.inSampleSize = sampleSize
            option.inPreferredConfig = Bitmap.Config.RGB_565
            option.inJustDecodeBounds = false
            bitmap = BitmapFactory.decodeStream(inputStream, null, option)
            val degree = readPictureDegree(filePath)
            bitmap = adjustPhotoRotation(bitmap!!, degree)
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        } catch (e : OutOfMemoryError) {
            //            java.lang.System.gc();
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
        return bitmap
    }
 
    private fun adjustPhotoRotation(bm: Bitmap, orientationDegree: Int): Bitmap {
 
        val matrix = Matrix()
        matrix.postRotate(orientationDegree.toFloat())
        return Bitmap.createBitmap(bm, 0, 0, bm.width, bm.height, matrix, true)
    }
 
    /**
     * 读取照片exif信息中的旋转角度
 
     * @param path
     * *            照片路径
     * *
     * @return 角度
     */
    private 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
    }
 
    private fun calculateMaxBitmapSize(context: Context): IntArray {
        val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val display = wm.defaultDisplay
        val size = Point()
        val width: Int
        val height: Int
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            display.getSize(size)
            width = size.x
            height = size.y
        } else {
            width = display.width
            height = display.height
        }
        return intArrayOf(width, height)
    }
 
    @Throws(IOException::class)
    private fun calculateBitmapSampleSize(file: File, maxHeight: Int, maxWidth: Int): Int {
        var inputStream: InputStream? = null
        val options = BitmapFactory.Options()
        options.inJustDecodeBounds = true
        try {
            inputStream = FileInputStream(file)
            BitmapFactory.decodeStream(inputStream, null, options) // Just get image size
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close()
                } catch (t: Throwable) {
                    // Do nothing
                }
            }
        }
        var sampleSize = 1
        while (options.outHeight / sampleSize > maxHeight || options.outWidth / sampleSize > maxWidth) {
            sampleSize = sampleSize shl 1
        }
        return sampleSize
    }
}