Jetpack Compose-拍照及图片保存及剪裁

拍照组件

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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Context
import android.graphics.Bitmap
import android.graphics.ImageDecoder
import android.os.Build
import android.provider.MediaStore
import android.util.Log
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.painter.BitmapPainter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.content.ContextCompat
import androidx.lifecycle.LifecycleOwner
import com.xhkjedu.zxs_android.R
import com.xhkjedu.zxs_android.common.CommonTheme
import com.xhkjedu.zxs_android.componts.ZImgLocalBg
import com.xhkjedu.zxs_android.componts.ZTextColorSizeComp
import com.xhkjedu.zxs_android.utils.BitmapUtils
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

@Composable
fun ZCameraComp(cancelAction: () -> Unit, okAction: (String) -> Unit) {
val TAG = "CameraComp"
val context = LocalContext.current
val lifecycleOwner = androidx.lifecycle.compose.LocalLifecycleOwner.current
val previewView = remember { PreviewView(context) }
var capturedImage by remember { mutableStateOf<Bitmap?>(null) }
val isTakingPhoto = remember { mutableStateOf(false) }
// 用于存储ImageCapture实例的变量
val imageCaptureInstance = remember { mutableStateOf<ImageCapture?>(null) }
// 创建相机执行器
val cameraExecutor = remember { Executors.newSingleThreadExecutor() }

val leftRightSpace = 120.dp

var leftRate by remember { mutableStateOf(0f) }
var topRate by remember { mutableStateOf(0f) }
var widthRate by remember { mutableStateOf(0f) }
var heightRate by remember { mutableStateOf(0f) }

// 初始化相机
LaunchedEffect(Unit) {
startCamera(previewView, context, imageCaptureInstance, lifecycleOwner, cameraExecutor)
}
// 释放相机资源
DisposableEffect(Unit) {
onDispose {
cameraExecutor.shutdown()
}
}
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Black)

) {
// 相机预览

Box(
modifier = Modifier
.fillMaxSize()
.padding(start = leftRightSpace, end = leftRightSpace)
.clip(RectangleShape)
) {
AndroidView(
factory = {
// 设置 PreviewView 的布局参数,使其填充父容器
previewView.layoutParams = android.view.ViewGroup.LayoutParams(
android.view.ViewGroup.LayoutParams.MATCH_PARENT,
android.view.ViewGroup.LayoutParams.MATCH_PARENT
)
previewView
},
modifier = Modifier
.fillMaxSize()
)
}

Box(
Modifier
.fillMaxSize()
.background(Color(0x66000000))
) {

Box(
Modifier
.width(520.dp)
.height(360.dp)
.border(width = 3.dp, Color.White, shape = CommonTheme.CornerM)
.align(Alignment.Center),
contentAlignment = Alignment.Center
) {
ZTextColorSizeComp("将作答内容放在屏幕中央", Color.White, 30.sp)
}



Box(
Modifier
.width(leftRightSpace)
.fillMaxHeight()
.align(Alignment.CenterEnd)
) {

Box(
Modifier
.size(70.dp)
.align(Alignment.TopCenter)
.offset(y = (70).dp)
.clickable {
cancelAction()
}
) {
ZImgLocalBg(R.drawable.camera_guanbi)
}
Box(
Modifier
.size(100.dp)
.align(Alignment.Center)
.clickable {
if (isTakingPhoto.value) {
return@clickable
}
isTakingPhoto.value = true
takePhoto(
context = context,
imageCapture = imageCaptureInstance.value,
cameraExecutor = cameraExecutor,
onImageCaptured = { bitmap ->
capturedImage = bitmap
}
)
}
) {
ZImgLocalBg(R.drawable.camera_paizhao)
}

Box(
Modifier
.size(70.dp)
.align(Alignment.BottomCenter)
.offset(y = (-70).dp)
) {
ZImgLocalBg(R.drawable.camera_xuanzhuan)
}

}

}


}

capturedImage?.let {
isTakingPhoto.value = false
Log.i(TAG, "width: " + it.width)
Log.i(TAG, "height: " + it.height)
Box(
modifier = Modifier
.fillMaxSize()
) {
Box(
modifier = Modifier
.fillMaxSize()
.padding(start = leftRightSpace, end = leftRightSpace)
) {
Image(
painter = BitmapPainter(
it.asImageBitmap()
),
modifier = Modifier
.fillMaxSize()
.background(Color(0xaa000000)),
contentScale = ContentScale.Crop,
contentDescription = "显示Bitmap图片"
)
ZResizeBoxComp() { left: Float, top: Float, width: Float, height: Float ->
Log.i(TAG, "ResizableBox width: " + width)
Log.i(TAG, "ResizableBox height: " + height)

leftRate = left
topRate = top
widthRate = width
heightRate = height

}

}

Box(
Modifier
.width(leftRightSpace)
.fillMaxHeight()
.background(Color.Black)
.align(Alignment.CenterEnd),
contentAlignment = Alignment.Center
) {

Column {
Box(
Modifier
.size(70.dp)
.clickable {
capturedImage = null
}
) {
ZImgLocalBg(R.drawable.camera_guanbi)
}

Spacer(Modifier.height(160.dp))
Box(
Modifier
.size(70.dp)
.clickable {
val img =
BitmapUtils.saveBitmapCropToFile(
it,
context,
leftRate,
topRate,
widthRate,
heightRate
)
img?.let {
Log.i(TAG, "CameraComp: ${img?.absolutePath}")
okAction(img.absolutePath)
}

}

) {
ZImgLocalBg(R.drawable.camera_queding)
}
}


}
}


}
}

private fun startCamera(
previewView: PreviewView,
context: Context,
imageCaptureInstance: MutableState<ImageCapture?>,
lifecycleOwner: LifecycleOwner,
cameraExecutor: ExecutorService
) {
val cameraProviderFuture = ProcessCameraProvider.getInstance(context)

cameraProviderFuture.addListener({
val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()

// 预览用例
val preview = Preview.Builder()
.build()
.also {
it.surfaceProvider = previewView.surfaceProvider
}
previewView.scaleType = PreviewView.ScaleType.FILL_CENTER
// 图像捕获用例
val imageCapture = ImageCapture.Builder()
.build()

imageCaptureInstance.value = imageCapture

// 选择后置摄像头
val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA

try {
// 解绑所有先前绑定的用例
cameraProvider.unbindAll()

// 绑定相机和用例
cameraProvider.bindToLifecycle(
lifecycleOwner, cameraSelector, preview, imageCapture
)

} catch (exc: Exception) {
Log.e("CameraX", "使用相机时发生错误", exc)
}

}, ContextCompat.getMainExecutor(context))
}

private fun takePhoto(
context: Context,
imageCapture: ImageCapture?,
cameraExecutor: ExecutorService,
onImageCaptured: (Bitmap) -> Unit
) {
// 获取ImageCapture实例
val imageCapture = imageCapture ?: return

// 创建带时间戳的文件名
val name = SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS", Locale.US)
.format(System.currentTimeMillis())

// 创建内容值
val contentValues = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, name)
put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg")
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) {
put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/CameraX-Image")
}
}

// 创建输出选项对象
val outputOptions = ImageCapture.OutputFileOptions
.Builder(
context.contentResolver,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
contentValues
)
.build()

// 拍摄照片
imageCapture.takePicture(
outputOptions,
ContextCompat.getMainExecutor(context),
object : ImageCapture.OnImageSavedCallback {
override fun onError(exc: ImageCaptureException) {
Log.e("CameraX", "拍照失败: ${exc.message}", exc)
}

@SuppressLint("ObsoleteSdkInt")
@Suppress("DEPRECATION")
override fun onImageSaved(output: ImageCapture.OutputFileResults) {
val savedUri = output.savedUri ?: return

// 将保存的URI转换为Bitmap
val bitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
val source = ImageDecoder.createSource(context.contentResolver, savedUri)
ImageDecoder.decodeBitmap(source)
} else {
MediaStore.Images.Media.getBitmap(context.contentResolver, savedUri)
}
onImageCaptured(bitmap)
Log.d("CameraX", "照片已保存到: $savedUri")
}
}
)
}

Bitmap剪裁

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
import android.content.Context
import android.graphics.Bitmap
import android.os.Environment
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

object BitmapUtils {
/**
* 将 Bitmap 保存为临时 JPEG 文件
*/
fun saveBitmapToFile(bitmap: Bitmap, context: Context): File? {
val timeStamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.getDefault()).format(Date())
return try {
// 创建临时文件
val tempFile = File.createTempFile(
timeStamp,
".jpg",
context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
)

// 压缩并保存 Bitmap 到文件
FileOutputStream(tempFile).use { out ->
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, out) // 质量 80%
}

tempFile
} catch (e: IOException) {
e.printStackTrace()
null
}
}

fun saveBitmapCropToFile(
bitmap: Bitmap,
context: Context,
leftRate: Float,
topRate: Float,
widthRate: Float,
heightRate: Float,
): File? {
val left = bitmap.width * leftRate
val top = bitmap.height * topRate
val width = bitmap.width * widthRate
val height = bitmap.height * heightRate
val cropBitmap =
Bitmap.createBitmap(bitmap, left.toInt(), top.toInt(), width.toInt(), height.toInt())
return saveBitmapToFile(cropBitmap, context)
}
}

调用

1
2
3
4
5
6
7
8
9
10
11
val img = BitmapUtils.saveBitmapCropToFile(
it,
context,
leftRate,
topRate,
widthRate,
heightRate
)
img?.let {
Log.i(TAG, "CameraComp: ${img?.absolutePath}")
}

在线图片剪裁

如果要剪裁在线的图片,我们要做如下环节

  • 图片下载到本地
  • 加载本地图片为Bitmap
  • 剪裁Bitmap
  • 保存剪裁后的图片到本地

其中图片的下载和加载为Bitmap也能合并成一步。

加载本地图片

1
2
3
4
5
6
7
8
fun loadBitmapFromFile(filePath: String): Bitmap? {
val imageFile = File(filePath)
return if (imageFile.exists()) {
BitmapFactory.decodeFile(filePath)
} else {
null
}
}

下载图片和加载也能合并成一步

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 下载图片并直接转为Bitmap
fun downloadImageToBitmap(urlString: String): Bitmap? {
try {
val url = URL(urlString)
val connection = url.openConnection() as HttpURLConnection
connection.setDoInput(true)
connection.connect()
val input = connection.getInputStream()
return BitmapFactory.decodeStream(input)
} catch (e: Exception) {
e.printStackTrace()
return null
}
}