-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBitmapX.kt
295 lines (269 loc) · 9.61 KB
/
BitmapX.kt
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
import android.content.ContentResolver
import android.content.Context
import android.content.res.Resources
import android.graphics.*
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import android.view.View
import androidx.core.content.FileProvider
import androidx.exifinterface.media.ExifInterface
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
///There will be multiple functions for the same task use as per your requirement
///get Bitmap From VectorResource
///if we import an SVG file to android studio it will be converted to xml file
///Use this method to convert that xml to bitmap
fun bitmapFromVector(context: Context, @DrawableRes vectorResId: Int): BitmapDescriptor {
val vectorDrawable = ContextCompat.getDrawable(context, vectorResId)
vectorDrawable!!.setBounds(0, 0, (vectorDrawable.intrinsicWidth),
(vectorDrawable.intrinsicHeight)
)
val bitmap = Bitmap.createBitmap(
(vectorDrawable.intrinsicWidth),
(vectorDrawable.intrinsicHeight),
Bitmap.Config.ARGB_8888
)
val canvas = Canvas(bitmap)
vectorDrawable.draw(canvas)
return bitmap
}
///Write a Bitmap into a file
fun File.writeBitmap(bitmap: Bitmap, format: Bitmap.CompressFormat = Bitmap.CompressFormat.PNG, quality: Int = 85) {
outputStream().use { out ->
bitmap.compress(format, quality, out)
out.flush()
}
}
///Save a bitmap into path
fun Bitmap.save(path: String, format: Bitmap.CompressFormat = Bitmap.CompressFormat.PNG, quality: Int = 85): Boolean {
return try {
val output = FileOutputStream(path)
this.compress(format, quality, output)
output.close()
true
} catch (e: Exception) {
e.printStackTrace()
false
}
}
///Save a bitmap into file
fun Bitmap.saveToFile(file: File, format: Bitmap.CompressFormat = Bitmap.CompressFormat.PNG, quality: Int = 85): Boolean {
return try {
FileOutputStream(file).use { out ->
this.compress(format, quality, out)
}
true
} catch (e: IOException) {
e.printStackTrace()
false
}
}
///Save a view to file
fun View.saveToFile(
file: File,
format: Bitmap.CompressFormat = Bitmap.CompressFormat.PNG,
quality: Int = 85
): Boolean {
return try{
var bitmap = Bitmap.createBitmap(this.width, this.height, Bitmap.Config.ARGB_8888)
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true)
val canvas = Canvas(bitmap)
this.draw(canvas)
bitmap
}catch (e: Exception) {
e.printStackTrace()
drawToBitmap()
}.saveToFile(file, format, quality)
}
///Convert a view into bitmap without drawing cache
fun View.toBitmap(): Bitmap {
return try{
var bitmap = Bitmap.createBitmap(this.width, this.height, Bitmap.Config.ARGB_8888)
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true)
val canvas = Canvas(bitmap)
this.draw(canvas)
bitmap
}catch (e: Exception) {
e.printStackTrace()
drawToBitmap()
}
}
///Convert View to Bitmap more of a screenshot with callback
///you can replace activity with other supported variants
fun View.getScreenShot(activity: Activity, callback: (Bitmap) -> Unit) {
activity.window?.let { window ->
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val locationOfViewInWindow = IntArray(2)
getLocationInWindow(locationOfViewInWindow)
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
PixelCopy.request(
window,
Rect(
locationOfViewInWindow[0],
locationOfViewInWindow[1],
locationOfViewInWindow[0] + width,
locationOfViewInWindow[1] + height
), bitmap, { copyResult ->
when (copyResult) {
PixelCopy.SUCCESS -> {
callback(bitmap)
}
// possible to handle other result codes ...
else -> {
}
}
},
Handler(Looper.getMainLooper())
)
} else try{
var bitmap = Bitmap.createBitmap(this.width, this.height, Bitmap.Config.ARGB_8888)
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true)
val canvas = Canvas(bitmap)
this.draw(canvas)
callback(bitmap)
}catch (e: Exception) {
e.printStackTrace()
callback(drawToBitmap())
}
} catch (e: IllegalArgumentException) {
// PixelCopy may throw IllegalArgumentException, make sure to handle it
e.printStackTrace()
}
}
}
@Suppress("DEPRECATION")
fun Uri.getBitmap(context: Context): Bitmap{
return if(Build.VERSION.SDK_INT < 28) {
MediaStore.Images.Media.getBitmap(
context.contentResolver,
this
)
} else {
val source = ImageDecoder.createSource(context.contentResolver, this)
ImageDecoder.decodeBitmap(source)
}
}
// Get average color of a bitmap
fun calculateAverageColor(bitmap: Bitmap, pixelSpacing: Int): Int {
var r = 0
var g = 0
var b = 0
val height = bitmap.height
val width = bitmap.width
var n = 0
val pixels = IntArray(width * height)
bitmap.getPixels(pixels, 0, width, 0, 0, width, height)
var i = 0
while (i < pixels.size) {
val color = pixels[i]
r += Color.red(color)
g += Color.green(color)
b += Color.blue(color)
n++
i += pixelSpacing
}
return Color.rgb(r / n, g / n, b / n)
}
///Correct orientation of a bitmap
///In some devices orientation might be wrong in those cases use this fun
fun Bitmap.rotateBitmapByOrientation(contentResolver: ContentResolver, uri: Uri): Bitmap? {
val matrix = Matrix()
var exif: ExifInterface?
return try {
val inputStream = contentResolver.openInputStream(uri)
inputStream?.let {
exif = ExifInterface(inputStream)
val orientation = exif!!.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED
)
when (orientation) {
ExifInterface.ORIENTATION_NORMAL -> return this
ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> matrix.setScale(-1f, 1f)
ExifInterface.ORIENTATION_ROTATE_180 -> matrix.setRotate(180f)
ExifInterface.ORIENTATION_FLIP_VERTICAL -> {
matrix.setRotate(180f)
matrix.postScale(-1f, 1f)
}
ExifInterface.ORIENTATION_TRANSPOSE -> {
matrix.setRotate(90f)
matrix.postScale(-1f, 1f)
}
ExifInterface.ORIENTATION_ROTATE_90 -> matrix.setRotate(90f)
ExifInterface.ORIENTATION_TRANSVERSE -> {
matrix.setRotate(-90f)
matrix.postScale(-1f, 1f)
}
ExifInterface.ORIENTATION_ROTATE_270 -> matrix.setRotate(-90f)
else -> return this
}
} ?: return this
val bmRotated = Bitmap.createBitmap(this, 0, 0, this.width, this.height, matrix, true)
this.recycle()
bmRotated.copy(Bitmap.Config.ARGB_8888, true)
} catch (e: Exception) {
e.printStackTrace()
null
}
}
val screenWidth: Int = Resources.getSystem().displayMetrics.widthPixels
val screenHeight: Int = Resources.getSystem().displayMetrics.heightPixels
///Scale Bitmap but keep aspect ratio
fun Bitmap.scaleBitmapAndKeepRation(
reqHeight: Int = screenHeight,
reqWidth: Int = screenWidth
): Bitmap {
val matrix = Matrix()
matrix.setRectToRect(
RectF(
0f, 0f, width.toFloat(),
height.toFloat()
),
RectF(0f, 0f, reqWidth.toFloat(), reqHeight.toFloat()),
Matrix.ScaleToFit.CENTER
)
return Bitmap.createBitmap(this, 0, 0, width, height, matrix, true)
}
///Rotate bitmap by angle
fun Bitmap.rotateBy(angle: Float): Bitmap {
val matrix = Matrix()
matrix.postRotate(angle)
return Bitmap.createBitmap(this, 0, 0, this.width / 2, this.height / 2, matrix, true)
}
///get Uri form file using file provider please check authority first
fun File.getUri(context: Context): Uri{
return FileProvider.getUriForFile(
context,
"${BuildConfig.APPLICATION_ID}.provider",
this
)
}
///Copy content of an uri to another file
fun Uri.copyToFile(file: File, context: Context): Boolean {
return try {
context.contentResolver.openInputStream(this).use { input ->
file.outputStream().use { output ->
input?.copyTo(output)
}
}
true
} catch (e: Exception) {
e.printStackTrace()
false
}
}
///Copy contents of a file to another file
fun File.copyTo(file: File): Boolean {
return try {
file.outputStream().use { output ->
this.inputStream().copyTo(output)
}
true
} catch (e: Exception) {
e.printStackTrace()
false
}
}