我有一张从 CameraX 拍摄的图像。
我想将图像保存到房间,但问题太多。所以我决定使用唯一的名称将图像保存到 cacheDir,然后保存房间的路径。
问题是当我获取数据并将其从线圈插入AsyncImage时,它不会加载任何内容。
这是我的代码。
感谢您的回复!
视图模型
try {
val cacheFile = File(context.cacheDir, "space_${System.currentTimeMillis()}.png")
Log.i("cachedfile", cacheFile.toString())
val outPutStream = FileOutputStream(cacheFile)
outPutStream.flush()
outPutStream.close()
addSpaceRepository.insertSpace(
space = Space(
id = "space_".plus(System.currentTimeMillis().toString()),
name = _uiState.value.spaceName.trim(),
color = _uiState.value.spaceColor.toArgb(),
iconName = _uiState.value.spaceIcon?.name ?: Icons.Rounded.Kitchen.name,
fileImageCache = cacheFile.path.toString()
)
)
} catch (e: Throwable) {
Log.e("erreur load file", "Cause : ${e.localizedMessage}")
}
屏幕可组合
cacheFilePath?.let {
AsyncImage(
modifier = Modifier.fillMaxSize(),
model = ImageRequest.Builder(context)
.data(File(it))
.build(),
contentDescription = "Image Space"
)
}
拍照
controller.takePicture(
ContextCompat.getMainExecutor(context),
object : OnImageCapturedCallback() {
override fun onCaptureSuccess(image: ImageProxy) {
super.onCaptureSuccess(image)
val matrix = Matrix().apply {
postRotate(image.imageInfo.rotationDegrees.toFloat())
}
val rotatedBitmap = Bitmap.createBitmap(
image.toBitmap(),
0,
0,
image.width,
image.height,
matrix,
true
)
onPhotoTaken(rotatedBitmap)
}
override fun onError(exception: ImageCaptureException) {
super.onError(exception)
Log.e("Camera launch", "Couldn't take photo: ", exception)
}
}
)
编辑
在 viewModel 函数中添加 bitmap.compress 就可以完成这项工作(我怎么忘了这样做......)
_uiState.value.spaceBitmap?.compress(Bitmap.CompressFormat.JPEG, 80, outPutStream)
但问题是我无法保存为PNG,它崩溃了。
我该怎么做?
将照片保存到本地时,不要忘记在 outPutStream 函数中添加压缩
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, outPutStream)