fix: preview performance
This commit is contained in:
1 parent
5dbd8f8341
commit
7bb05b86bb
9 files changed
+187
-223
No files matched your search
@@ -182,7 +182,8 @@ fun NavigationHost(
|
||||
galleryViewModel = galleryViewModel,
|
||||
onGalleryClick = {
|
||||
navController.navigate(Routes.GALLERY)
|
||||
if (galleryViewModel.latestPhoto.value != null) {
|
||||
val latestPhoto = galleryViewModel.latestPhoto.value
|
||||
if (latestPhoto != null && System.currentTimeMillis() - latestPhoto.dateAdded < 3 * 60 * 1000) {
|
||||
navController.navigate(Routes.photoDetail(0))
|
||||
}
|
||||
},
|
||||
|
||||
@@ -70,12 +70,13 @@ class GalleryRepository(private val context: Context) {
|
||||
photoIds.take(limit).forEach { id ->
|
||||
val photoFile = PhotoManager.getPhotoFile(context, id)
|
||||
if (photoFile.exists()) {
|
||||
val previewFile = PhotoManager.getPreviewFile(context, id)
|
||||
photos.add(
|
||||
PhotoData(
|
||||
id = id,
|
||||
uri = Uri.fromFile(photoFile),
|
||||
thumbnailUri = Uri.fromFile(PhotoManager.getThumbnailFile(context, id)),
|
||||
previewUri = Uri.fromFile(PhotoManager.getPreviewFile(context, id)),
|
||||
previewUri = Uri.fromFile(if (previewFile.exists()) previewFile else photoFile),
|
||||
displayName = photoFile.name,
|
||||
dateAdded = photoFile.lastModified() / 1000,
|
||||
dateTaken = photoFile.lastModified(),
|
||||
@@ -88,5 +89,3 @@ class GalleryRepository(private val context: Context) {
|
||||
return photos
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,10 +10,13 @@ import com.hinnka.mycamera.camera.CaptureInfo
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
import java.util.*
|
||||
import kotlin.math.max
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/**
|
||||
* 照片管理器
|
||||
@@ -67,14 +70,12 @@ object PhotoManager {
|
||||
* @param context Context
|
||||
* @param bitmap 原始 Bitmap 图片
|
||||
* @param metadata 编辑元数据(LUT、边框等)
|
||||
* @param previewBitmap 预览图(用于生成缩略图)
|
||||
* @param captureInfo 拍摄信息(用于写入 EXIF)
|
||||
*/
|
||||
suspend fun savePhoto(
|
||||
context: Context,
|
||||
bitmap: Bitmap,
|
||||
metadata: PhotoMetadata,
|
||||
previewBitmap: Bitmap? = null,
|
||||
captureInfo: CaptureInfo? = null,
|
||||
): String? {
|
||||
return withContext(Dispatchers.IO) {
|
||||
@@ -102,7 +103,16 @@ object PhotoManager {
|
||||
FileOutputStream(photoFile).use { out ->
|
||||
bitmap.compress(Bitmap.CompressFormat.JPEG, 95, out)
|
||||
}
|
||||
// EXIF 必须在原图保存后写入
|
||||
}
|
||||
|
||||
// 任务 2: 保存元数据 JSON
|
||||
launch {
|
||||
metadataFile.writeText(metadataJson)
|
||||
}
|
||||
|
||||
// 任务 3: EXIF 必须在原图保存后写入
|
||||
launch {
|
||||
saveOriginalJob.await()
|
||||
captureInfo?.copy(
|
||||
imageWidth = bitmap.width,
|
||||
imageHeight = bitmap.height,
|
||||
@@ -111,37 +121,21 @@ object PhotoManager {
|
||||
}
|
||||
}
|
||||
|
||||
// 任务 2: 保存元数据 JSON
|
||||
val saveMetadataJob = async {
|
||||
metadataFile.writeText(metadataJson)
|
||||
// 任务 4: 生成并保存预览图
|
||||
launch {
|
||||
saveOriginalJob.await()
|
||||
savePreviewFileIfNeed(photoFile, previewFile)
|
||||
}
|
||||
|
||||
// 任务 3: 生成并保存缩略图
|
||||
val saveThumbnailJob = async {
|
||||
if (previewBitmap != null) {
|
||||
// 从预览图生成缩略图,更高效
|
||||
saveThumbnail(previewBitmap, thumbnailFile)
|
||||
} else {
|
||||
// 没有预览图时,需要等原图保存完成后再生成
|
||||
saveOriginalJob.await()
|
||||
generateThumbnail(photoFile, thumbnailFile)
|
||||
}
|
||||
}
|
||||
|
||||
// 任务 4: 保存 LUT 预览图
|
||||
val savePreviewJob = async {
|
||||
if (previewBitmap != null) {
|
||||
FileOutputStream(previewFile).use { out ->
|
||||
previewBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out)
|
||||
}
|
||||
}
|
||||
// 任务 5: 生成并保存缩略图
|
||||
val thumbnailJob = async {
|
||||
saveOriginalJob.await()
|
||||
generateThumbnail(photoFile, thumbnailFile)
|
||||
}
|
||||
|
||||
// 等待所有任务完成
|
||||
saveOriginalJob.await()
|
||||
saveMetadataJob.await()
|
||||
saveThumbnailJob.await()
|
||||
savePreviewJob.await()
|
||||
thumbnailJob.await()
|
||||
}
|
||||
|
||||
Log.d(TAG, "Photo saved: $photoId")
|
||||
@@ -153,14 +147,22 @@ object PhotoManager {
|
||||
}
|
||||
}
|
||||
|
||||
private fun saveThumbnail(source: Bitmap, targetFile: File) {
|
||||
private fun savePreviewFileIfNeed(sourceFile: File, targetFile: File) {
|
||||
try {
|
||||
val targetSize = 512
|
||||
val thumbnail = ThumbnailUtils.extractThumbnail(source, targetSize, targetSize)
|
||||
FileOutputStream(targetFile).use { out ->
|
||||
thumbnail.compress(Bitmap.CompressFormat.JPEG, 80, out)
|
||||
val option = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeFile(sourceFile.absolutePath, option)
|
||||
val maxSide = max(option.outWidth, option.outHeight)
|
||||
if (maxSide > 3840) {
|
||||
val inSampleSize = (maxSide / 2560f).roundToInt().coerceAtLeast(1)
|
||||
option.inSampleSize = inSampleSize
|
||||
option.inJustDecodeBounds = false
|
||||
val bitmap = BitmapFactory.decodeFile(sourceFile.absolutePath, option)
|
||||
if (bitmap != null) {
|
||||
FileOutputStream(targetFile).use { out ->
|
||||
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out)
|
||||
}
|
||||
}
|
||||
}
|
||||
thumbnail.recycle()
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to save thumbnail from source", e)
|
||||
}
|
||||
@@ -170,7 +172,6 @@ object PhotoManager {
|
||||
* 生成缩略图
|
||||
*/
|
||||
private fun generateThumbnail(sourceFile: File, targetFile: File) {
|
||||
|
||||
try {
|
||||
val options = BitmapFactory.Options().apply {
|
||||
inJustDecodeBounds = true
|
||||
@@ -183,6 +184,7 @@ object PhotoManager {
|
||||
options.inJustDecodeBounds = false
|
||||
|
||||
val bitmap = BitmapFactory.decodeFile(sourceFile.absolutePath, options)
|
||||
|
||||
if (bitmap != null) {
|
||||
val thumbnail = ThumbnailUtils.extractThumbnail(bitmap, targetSize, targetSize)
|
||||
FileOutputStream(targetFile).use { out ->
|
||||
@@ -286,6 +288,7 @@ object PhotoManager {
|
||||
val photoFile = File(photoDir, PHOTO_FILE)
|
||||
val metadataFile = File(photoDir, METADATA_FILE)
|
||||
val thumbnailFile = File(photoDir, THUMBNAIL_FILE)
|
||||
val previewFile = File(photoDir, PREVIEW_FILE)
|
||||
|
||||
// 1. 复制文件
|
||||
context.contentResolver.openInputStream(uri)?.use { input ->
|
||||
@@ -299,6 +302,7 @@ object PhotoManager {
|
||||
metadataFile.writeText(metadata.toJson())
|
||||
|
||||
// 3. 生成缩略图
|
||||
savePreviewFileIfNeed(photoFile, previewFile)
|
||||
generateThumbnail(photoFile, thumbnailFile)
|
||||
|
||||
Log.d(TAG, "Photo imported: $photoId")
|
||||
|
||||
@@ -21,6 +21,7 @@ import androidx.compose.ui.unit.dp
|
||||
import coil.compose.AsyncImage
|
||||
import coil.request.ImageRequest
|
||||
import com.hinnka.mycamera.gallery.PhotoData
|
||||
import com.hinnka.mycamera.lut.PhotoTransformation
|
||||
import com.hinnka.mycamera.viewmodel.GalleryViewModel
|
||||
|
||||
/**
|
||||
@@ -46,17 +47,11 @@ fun GalleryThumbnail(
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
if (latestPhoto != null) {
|
||||
// 显示最近的照片缩略图,优先使用带 LUT/边框 的预览图
|
||||
val imageSource = if (latestPhoto.metadata?.lutId != null || latestPhoto.metadata?.frameId != null) {
|
||||
latestPhoto.previewUri
|
||||
} else {
|
||||
latestPhoto.thumbnailUri
|
||||
}
|
||||
|
||||
AsyncImage(
|
||||
model = ImageRequest.Builder(context)
|
||||
.data(imageSource)
|
||||
.data(latestPhoto.thumbnailUri)
|
||||
.crossfade(true)
|
||||
.transformations(viewModel.getPhotoTransformation(latestPhoto))
|
||||
.build(),
|
||||
contentDescription = "Gallery",
|
||||
contentScale = ContentScale.Crop,
|
||||
|
||||
@@ -131,7 +131,7 @@ fun GalleryScreen(
|
||||
}
|
||||
},
|
||||
colors = TopAppBarDefaults.topAppBarColors(
|
||||
containerColor = Color.Black
|
||||
containerColor = Color(0xFF434A5D)
|
||||
)
|
||||
)
|
||||
},
|
||||
@@ -201,7 +201,7 @@ fun GalleryScreen(
|
||||
}
|
||||
}
|
||||
},
|
||||
containerColor = Color.Black,
|
||||
containerColor = Color(0xFF434A5D),
|
||||
modifier = modifier
|
||||
) { paddingValues ->
|
||||
Box(
|
||||
|
||||
@@ -462,7 +462,7 @@ private fun ZoomableImage(
|
||||
) {
|
||||
AsyncImage(
|
||||
model = ImageRequest.Builder(context)
|
||||
.data(photo.uri)
|
||||
.data(photo.previewUri)
|
||||
.crossfade(true)
|
||||
.transformations(viewModel.getPhotoTransformation(photo))
|
||||
.build(),
|
||||
|
||||
@@ -217,7 +217,7 @@ fun PhotoEditScreen(
|
||||
// 加载中或尚无预览时显示原图
|
||||
AsyncImage(
|
||||
model = ImageRequest.Builder(context)
|
||||
.data(currentPhoto.uri)
|
||||
.data(currentPhoto.previewUri)
|
||||
.crossfade(true)
|
||||
.build(),
|
||||
contentDescription = stringResource(R.string.original),
|
||||
|
||||
@@ -2,7 +2,6 @@ package com.hinnka.mycamera.viewmodel
|
||||
|
||||
import android.app.Application
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.SurfaceTexture
|
||||
import android.hardware.camera2.CameraCharacteristics
|
||||
import android.media.Image
|
||||
@@ -28,73 +27,66 @@ import com.hinnka.mycamera.lut.LutConfig
|
||||
import com.hinnka.mycamera.lut.LutImageProcessor
|
||||
import com.hinnka.mycamera.lut.LutInfo
|
||||
import com.hinnka.mycamera.lut.LutManager
|
||||
import com.hinnka.mycamera.utils.BitmapUtils.toByteArray
|
||||
import com.hinnka.mycamera.utils.OrientationObserver
|
||||
import com.hinnka.mycamera.utils.ShutterSoundPlayer
|
||||
import com.hinnka.mycamera.utils.YuvProcessor
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.*
|
||||
import kotlinx.coroutines.flow.*
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlin.math.min
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/**
|
||||
* 相机 ViewModel
|
||||
* 使用 Camera2Controller 支持隐藏摄像头
|
||||
*/
|
||||
class CameraViewModel(application: Application) : AndroidViewModel(application) {
|
||||
|
||||
|
||||
companion object {
|
||||
private const val TAG = "CameraViewModel"
|
||||
}
|
||||
|
||||
|
||||
private val cameraController = Camera2Controller(application)
|
||||
|
||||
|
||||
// 用户偏好设置仓库
|
||||
private val userPreferencesRepository = UserPreferencesRepository(application)
|
||||
|
||||
|
||||
// LUT 管理器
|
||||
private val lutManager = LutManager(application)
|
||||
private val lutImageProcessor = LutImageProcessor()
|
||||
|
||||
|
||||
// 计费管理器
|
||||
private val billingManager = com.hinnka.mycamera.billing.BillingManagerImpl(application)
|
||||
val isPurchased = billingManager.isPurchased
|
||||
|
||||
|
||||
// 边框管理器
|
||||
private val frameManager = FrameManager(application)
|
||||
private val frameRenderer = FrameRenderer(application)
|
||||
private val photoProcessor = PhotoProcessor(lutManager, lutImageProcessor, frameManager, frameRenderer)
|
||||
|
||||
|
||||
// 快门音效播放器
|
||||
private val shutterSoundPlayer = ShutterSoundPlayer(application)
|
||||
|
||||
val state: StateFlow<CameraState> = cameraController.state
|
||||
|
||||
|
||||
// 照片保存完成事件
|
||||
private val _imageSavedEvent = MutableSharedFlow<Unit>()
|
||||
val imageSavedEvent: SharedFlow<Unit> = _imageSavedEvent.asSharedFlow()
|
||||
|
||||
|
||||
// LUT 相关状态
|
||||
var currentLutConfig: LutConfig? by mutableStateOf(null)
|
||||
private set
|
||||
|
||||
|
||||
var currentLutId: String? by mutableStateOf(null)
|
||||
private set
|
||||
|
||||
|
||||
var availableLutList: List<LutInfo> by mutableStateOf(emptyList())
|
||||
private set
|
||||
|
||||
|
||||
// LUT 预览图缓存(lutId -> 预览Bitmap)
|
||||
var lutPreviewBitmaps: Map<String, Bitmap> by mutableStateOf(emptyMap())
|
||||
private set
|
||||
|
||||
|
||||
// 原始预览帧(用于生成 LUT 预览)
|
||||
private var rawPreviewFrame: Bitmap? = null
|
||||
|
||||
|
||||
// 是否正在生成预览
|
||||
private var isGeneratingPreviews = false
|
||||
|
||||
@@ -115,18 +107,18 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
|
||||
// 付费弹窗状态
|
||||
var showPaymentDialog by mutableStateOf(false)
|
||||
|
||||
|
||||
// 新增设置项 StateFlow
|
||||
val showLevelIndicator: Flow<Boolean> = userPreferencesRepository.userPreferences.map { it.showLevelIndicator }
|
||||
val shutterSoundEnabled: Flow<Boolean> = userPreferencesRepository.userPreferences.map { it.shutterSoundEnabled }
|
||||
val volumeKeyCapture: Flow<Boolean> = userPreferencesRepository.userPreferences.map { it.volumeKeyCapture }
|
||||
val autoSaveAfterCapture: Flow<Boolean> = userPreferencesRepository.userPreferences.map { it.autoSaveAfterCapture }
|
||||
|
||||
|
||||
private var isShutterSoundEnabled = true
|
||||
|
||||
|
||||
// 保存当前的 SurfaceTexture 以便切换摄像头时重用
|
||||
private var currentSurfaceTexture: SurfaceTexture? = null
|
||||
|
||||
|
||||
init {
|
||||
cameraController.initialize()
|
||||
cameraController.onImageCaptured = { image, captureInfo ->
|
||||
@@ -134,21 +126,21 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
saveImage(image, captureInfo)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 监听快门声音设置
|
||||
viewModelScope.launch {
|
||||
userPreferencesRepository.userPreferences.collect {
|
||||
isShutterSoundEnabled = it.shutterSoundEnabled
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 设置快门音效回调
|
||||
cameraController.onPlayShutterSound = {
|
||||
if (isShutterSoundEnabled) {
|
||||
shutterSoundPlayer.play()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 初始化 LUT 管理器
|
||||
lutManager.initialize()
|
||||
availableLutList = lutManager.getAvailableLuts()
|
||||
@@ -156,7 +148,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
// 初始化边框管理器
|
||||
frameManager.initialize()
|
||||
availableFrameList = frameManager.getAvailableFrames()
|
||||
|
||||
|
||||
// 加载用户偏好设置
|
||||
viewModelScope.launch {
|
||||
val prefs = userPreferencesRepository.userPreferences.firstOrNull()
|
||||
@@ -168,7 +160,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
} catch (e: IllegalArgumentException) {
|
||||
// 如果保存的值无效,使用默认值
|
||||
}
|
||||
|
||||
|
||||
// 应用保存的 LUT 配置
|
||||
if (prefs.lutId != null) {
|
||||
setLut(prefs.lutId)
|
||||
@@ -178,7 +170,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
defaultLut?.let { setLut(it.id) }
|
||||
}
|
||||
setLutIntensity(prefs.lutIntensity)
|
||||
|
||||
|
||||
// 应用保存的边框配置
|
||||
if (prefs.frameId != null) {
|
||||
currentFrameId = prefs.frameId
|
||||
@@ -186,7 +178,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
currentShowAppBranding = prefs.showAppBranding
|
||||
|
||||
showHistogram = prefs.showHistogram
|
||||
|
||||
|
||||
// 应用保存的网格线设置
|
||||
cameraController.setShowGrid(prefs.showGrid)
|
||||
} else {
|
||||
@@ -196,7 +188,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 打开相机(Camera2 接口)
|
||||
*/
|
||||
@@ -204,14 +196,14 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
currentSurfaceTexture = surfaceTexture
|
||||
cameraController.openCamera(surfaceTexture)
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 关闭相机
|
||||
*/
|
||||
fun closeCamera() {
|
||||
cameraController.closeCamera()
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 检查相机状态并在必要时恢复
|
||||
*/
|
||||
@@ -223,13 +215,13 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 拍照(带延时拍摄支持)
|
||||
*/
|
||||
fun capture() {
|
||||
val timerSeconds = state.value.timerSeconds
|
||||
|
||||
|
||||
// 检查 VIP 权限
|
||||
val currentLut = getLutInfo(currentLutId ?: "")
|
||||
if (currentLut?.isVip == true && !isPurchased.value) {
|
||||
@@ -253,7 +245,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
cameraController.capture()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 切换摄像头(前后置切换)
|
||||
*/
|
||||
@@ -262,7 +254,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
reopenCamera()
|
||||
zoomRatioByMain = 1f
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 切换到指定的镜头类型
|
||||
*/
|
||||
@@ -270,7 +262,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
cameraController.switchToCameraId(cameraId)
|
||||
reopenCamera()
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 重新打开相机(切换摄像头后使用)
|
||||
*/
|
||||
@@ -279,35 +271,35 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
cameraController.openCamera(texture)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取所有后置摄像头
|
||||
*/
|
||||
fun getBackCameras(): List<com.hinnka.mycamera.camera.CameraInfo> {
|
||||
return cameraController.getBackCameras()
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 设置曝光补偿
|
||||
*/
|
||||
fun setExposureCompensation(value: Int) {
|
||||
cameraController.setExposureCompensation(value)
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 设置 ISO
|
||||
*/
|
||||
fun setIso(value: Int) {
|
||||
cameraController.setIso(value)
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 设置快门速度
|
||||
*/
|
||||
fun setShutterSpeed(value: Long) {
|
||||
cameraController.setShutterSpeed(value)
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 设置变焦倍数
|
||||
*/
|
||||
@@ -317,7 +309,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
val intrinsicZoomRatio = cameraInfo?.intrinsicZoomRatio ?: 1.0f
|
||||
cameraController.setZoomRatio(ratio / intrinsicZoomRatio)
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 设置画面比例
|
||||
*/
|
||||
@@ -328,7 +320,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
userPreferencesRepository.saveAspectRatio(ratio.name)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 点击对焦
|
||||
*/
|
||||
@@ -337,12 +329,14 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
}
|
||||
|
||||
fun toggleFlash() {
|
||||
cameraController.setFlashMode(when (state.value.flashMode) {
|
||||
0 -> 1
|
||||
1 -> 2
|
||||
2 -> 0
|
||||
else -> 0
|
||||
})
|
||||
cameraController.setFlashMode(
|
||||
when (state.value.flashMode) {
|
||||
0 -> 1
|
||||
1 -> 2
|
||||
2 -> 0
|
||||
else -> 0
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -365,23 +359,23 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
fun setShutterSpeedAuto(enabled: Boolean) {
|
||||
cameraController.setShutterSpeedAuto(enabled)
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 设置白平衡模式
|
||||
*/
|
||||
fun setAwbMode(mode: Int) {
|
||||
cameraController.setAwbMode(mode)
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 设置白平衡色温
|
||||
*/
|
||||
fun setAwbTemperature(kelvin: Int) {
|
||||
cameraController.setAwbTemperature(kelvin)
|
||||
}
|
||||
|
||||
|
||||
// ==================== 计费相关方法 ====================
|
||||
|
||||
|
||||
/**
|
||||
* 发起购买
|
||||
*/
|
||||
@@ -390,7 +384,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
}
|
||||
|
||||
// ==================== LUT 相关方法 ====================
|
||||
|
||||
|
||||
/**
|
||||
* 设置当前 LUT
|
||||
*/
|
||||
@@ -405,13 +399,13 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 保存到用户偏好设置
|
||||
viewModelScope.launch {
|
||||
userPreferencesRepository.saveLutConfig(lutId, state.value.lutIntensity)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 设置 LUT 强度
|
||||
*/
|
||||
@@ -422,21 +416,21 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
userPreferencesRepository.saveLutIntensity(intensity)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取 LUT 信息
|
||||
*/
|
||||
fun getLutInfo(id: String): LutInfo? {
|
||||
return lutManager.getLutInfo(id)
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 预加载 LUT
|
||||
*/
|
||||
fun preloadLut(id: String) {
|
||||
lutManager.preloadLut(id)
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 从相机捕获预览帧并生成所有 LUT 的预览图
|
||||
*/
|
||||
@@ -445,9 +439,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
Log.d(TAG, "Already generating previews, skipping")
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
isGeneratingPreviews = true
|
||||
|
||||
|
||||
// 设置回调接收原始 YUV 预览帧
|
||||
cameraController.onPreviewFrameCaptured = { bitmap ->
|
||||
viewModelScope.launch(Dispatchers.Default) {
|
||||
@@ -455,15 +449,15 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
// 保存原始帧
|
||||
rawPreviewFrame?.recycle()
|
||||
rawPreviewFrame = bitmap
|
||||
|
||||
|
||||
// 生成所有 LUT 预览
|
||||
val newPreviews = mutableMapOf<String, Bitmap>()
|
||||
|
||||
|
||||
availableLutList.forEach { lutInfo ->
|
||||
val lutConfig = withContext(Dispatchers.IO) {
|
||||
lutManager.loadLut(lutInfo.id)
|
||||
}
|
||||
|
||||
|
||||
if (lutConfig != null) {
|
||||
val previewBitmap = lutImageProcessor.applyLut(
|
||||
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, false),
|
||||
@@ -473,7 +467,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
newPreviews[lutInfo.id] = previewBitmap
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 更新预览图
|
||||
withContext(Dispatchers.Main) {
|
||||
lutPreviewBitmaps.values.forEach { it.recycle() }
|
||||
@@ -487,11 +481,11 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 触发捕获
|
||||
cameraController.capturePreviewFrame()
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 将 YUV Image 转换为 Bitmap
|
||||
*/
|
||||
@@ -501,25 +495,25 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
val yPlane = planes[0]
|
||||
val uPlane = planes[1]
|
||||
val vPlane = planes[2]
|
||||
|
||||
|
||||
val yBuffer = yPlane.buffer
|
||||
val uBuffer = uPlane.buffer
|
||||
val vBuffer = vPlane.buffer
|
||||
|
||||
|
||||
val ySize = yBuffer.remaining()
|
||||
val uSize = uBuffer.remaining()
|
||||
val vSize = vBuffer.remaining()
|
||||
|
||||
|
||||
val nv21 = ByteArray(ySize + uSize + vSize)
|
||||
|
||||
|
||||
// 复制 Y 数据
|
||||
yBuffer.get(nv21, 0, ySize)
|
||||
|
||||
|
||||
// 交织 U 和 V 数据为 NV21 格式
|
||||
val pixelStride = vPlane.pixelStride
|
||||
val rowStride = vPlane.rowStride
|
||||
var pos = ySize
|
||||
|
||||
|
||||
for (row in 0 until image.height / 2) {
|
||||
for (col in 0 until image.width / 2) {
|
||||
val vuPos = row * rowStride + col * pixelStride
|
||||
@@ -527,9 +521,10 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
nv21[pos++] = uBuffer.get(vuPos)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 使用 android.graphics.YuvImage 转换为 Bitmap
|
||||
val yuvImage = android.graphics.YuvImage(nv21, android.graphics.ImageFormat.NV21, image.width, image.height, null)
|
||||
val yuvImage =
|
||||
android.graphics.YuvImage(nv21, android.graphics.ImageFormat.NV21, image.width, image.height, null)
|
||||
val out = java.io.ByteArrayOutputStream()
|
||||
yuvImage.compressToJpeg(android.graphics.Rect(0, 0, image.width, image.height), 100, out)
|
||||
val imageBytes = out.toByteArray()
|
||||
@@ -539,7 +534,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 清除 LUT 预览缓存
|
||||
*/
|
||||
@@ -549,7 +544,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
rawPreviewFrame?.recycle()
|
||||
rawPreviewFrame = null
|
||||
}
|
||||
|
||||
|
||||
// ==================== 边框相关方法 ====================
|
||||
|
||||
/**
|
||||
@@ -584,9 +579,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
userPreferencesRepository.saveShowHistogram(show)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// ==================== 延时拍摄和网格线相关方法 ====================
|
||||
|
||||
|
||||
/**
|
||||
* 切换延时拍摄档位(0s → 3s → 5s → 10s → 0s)
|
||||
*/
|
||||
@@ -601,7 +596,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
}
|
||||
cameraController.setTimerSeconds(nextTimer)
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 切换网格线显示
|
||||
*/
|
||||
@@ -613,9 +608,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
userPreferencesRepository.saveShowGrid(newShowGrid)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// ==================== 新增设置项方法 ====================
|
||||
|
||||
|
||||
/**
|
||||
* 设置是否显示水平仪
|
||||
*/
|
||||
@@ -624,7 +619,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
userPreferencesRepository.saveShowLevelIndicator(show)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 设置是否启用快门声音
|
||||
*/
|
||||
@@ -633,7 +628,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
userPreferencesRepository.saveShutterSoundEnabled(enabled)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 设置是否启用音量键拍摄
|
||||
*/
|
||||
@@ -642,7 +637,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
userPreferencesRepository.saveVolumeKeyCapture(enabled)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 设置是否拍摄后自动保存
|
||||
*/
|
||||
@@ -657,17 +652,17 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
*/
|
||||
private suspend fun saveImage(image: Image, captureInfo: CaptureInfo) {
|
||||
val context = getApplication<Application>()
|
||||
|
||||
|
||||
// 保存当前 LUT 信息用于元数据
|
||||
val lutIdToSave = currentLutId
|
||||
val lutIntensityToSave = state.value.lutIntensity
|
||||
|
||||
val aspectRatio = state.value.aspectRatio
|
||||
|
||||
|
||||
// 保存当前边框信息用于元数据
|
||||
val frameIdToSave = currentFrameId
|
||||
val showAppBrandingToSave = currentShowAppBranding
|
||||
|
||||
|
||||
// 获取是否自动保存设置
|
||||
val shouldAutoSave = autoSaveAfterCapture.firstOrNull() ?: false
|
||||
|
||||
@@ -676,21 +671,21 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
val sensorOrientation = cameraController.getSensorOrientation()
|
||||
val lensFacing = cameraController.getLensFacing()
|
||||
val deviceRotation = OrientationObserver.rotationDegrees.toInt()
|
||||
|
||||
|
||||
val rotation = if (lensFacing == CameraCharacteristics.LENS_FACING_FRONT) {
|
||||
(sensorOrientation - deviceRotation + 360) % 360
|
||||
} else {
|
||||
(sensorOrientation + deviceRotation) % 360
|
||||
}
|
||||
|
||||
|
||||
// Step 1: 使用 YuvProcessor 处理 YUV 图像(旋转、裁切、转换为 Bitmap)
|
||||
val bitmap = withContext(Dispatchers.Default) {
|
||||
YuvProcessor.processAndToBitmap(image, aspectRatio, rotation)
|
||||
}
|
||||
|
||||
|
||||
// 关闭 Image 资源
|
||||
image.close()
|
||||
|
||||
|
||||
// 创建统一的 PhotoMetadata,包含编辑配置和拍摄信息
|
||||
val metadata = PhotoMetadata(
|
||||
// 编辑配置
|
||||
@@ -709,81 +704,51 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
aperture = captureInfo.formatAperture(),
|
||||
)
|
||||
|
||||
val previewBitmap: Bitmap
|
||||
|
||||
if (shouldAutoSave) {
|
||||
// 如果开启自动保存,先处理图片,再并行执行导出和本地保存
|
||||
|
||||
// 处理完整图片(应用 LUT 和边框)
|
||||
val processedBitmap = withContext(Dispatchers.Default) {
|
||||
photoProcessor.process(context, bitmap, metadata)
|
||||
}
|
||||
|
||||
// 生成预览图(从已处理的图片缩放)
|
||||
previewBitmap = withContext(Dispatchers.Default) {
|
||||
val inSampleSize = (min(processedBitmap.width, processedBitmap.height) / 1080f).roundToInt().coerceAtLeast(1)
|
||||
Bitmap.createScaledBitmap(processedBitmap, processedBitmap.width / inSampleSize, processedBitmap.height / inSampleSize, false)
|
||||
}
|
||||
|
||||
// 并行执行:导出到系统相册 + 保存到本地
|
||||
coroutineScope {
|
||||
// 任务 1: 导出到系统相册
|
||||
val exportJob = async(Dispatchers.IO) {
|
||||
val filename = "PhotonCamera_${java.text.SimpleDateFormat("yyyyMMdd_HHmmss", java.util.Locale.US).format(java.util.Date())}.jpg"
|
||||
val contentValues = android.content.ContentValues().apply {
|
||||
put(android.provider.MediaStore.MediaColumns.DISPLAY_NAME, filename)
|
||||
put(android.provider.MediaStore.MediaColumns.MIME_TYPE, "image/jpeg")
|
||||
put(android.provider.MediaStore.MediaColumns.RELATIVE_PATH, android.os.Environment.DIRECTORY_DCIM + "/PhotonCamera")
|
||||
}
|
||||
|
||||
val uri = context.contentResolver.insert(
|
||||
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
|
||||
contentValues
|
||||
)
|
||||
|
||||
uri?.let {
|
||||
context.contentResolver.openOutputStream(it)?.use { outputStream ->
|
||||
processedBitmap.compress(Bitmap.CompressFormat.JPEG, 95, outputStream)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 任务 2: 保存到本地(使用原始 bitmap)
|
||||
val saveLocalJob = async {
|
||||
PhotoManager.savePhoto(context, bitmap, metadata, previewBitmap, captureInfo)
|
||||
}
|
||||
|
||||
exportJob.await()
|
||||
val photoId = saveLocalJob.await()
|
||||
|
||||
coroutineScope {
|
||||
// 保存原始照片到数据库
|
||||
launch {
|
||||
val photoId = PhotoManager.savePhoto(context, bitmap, metadata, captureInfo)
|
||||
|
||||
if (photoId != null) {
|
||||
Log.d(TAG, "Image saved: $photoId, LUT: $lutIdToSave, Frame: $frameIdToSave, AutoSave: true")
|
||||
Log.d(TAG, "Image saved: $photoId, LUT: $lutIdToSave, Frame: $frameIdToSave")
|
||||
_imageSavedEvent.emit(Unit)
|
||||
} else {
|
||||
Log.e(TAG, "Failed to save image via PhotoManager")
|
||||
}
|
||||
}
|
||||
|
||||
processedBitmap.recycle()
|
||||
previewBitmap.recycle()
|
||||
} else {
|
||||
// 原有逻辑:生成预览图/缩略图源(缩小比例以提高性能)
|
||||
previewBitmap = withContext(Dispatchers.Default) {
|
||||
val inSampleSize = (min(bitmap.width, bitmap.height) / 1080f).roundToInt().coerceAtLeast(1)
|
||||
val scaledBitmap = Bitmap.createScaledBitmap(bitmap, bitmap.width / inSampleSize, bitmap.height / inSampleSize, false)
|
||||
photoProcessor.process(context, scaledBitmap, metadata)
|
||||
}
|
||||
|
||||
// 使用 PhotoManager 统一管理保存,并写入 EXIF
|
||||
val photoId = PhotoManager.savePhoto(context, bitmap, metadata, previewBitmap, captureInfo)
|
||||
|
||||
previewBitmap.recycle()
|
||||
|
||||
if (photoId != null) {
|
||||
Log.d(TAG, "Image saved: $photoId, LUT: $lutIdToSave, Frame: $frameIdToSave, AutoSave: false")
|
||||
_imageSavedEvent.emit(Unit)
|
||||
} else {
|
||||
Log.e(TAG, "Failed to save image via PhotoManager")
|
||||
|
||||
// 如果启用自动保存,导出处理后的图片到系统相册
|
||||
if (shouldAutoSave) {
|
||||
launch {
|
||||
val processedBitmap = withContext(Dispatchers.Default) {
|
||||
photoProcessor.process(context, bitmap, metadata)
|
||||
}
|
||||
|
||||
val filename = "PhotonCamera_${
|
||||
java.text.SimpleDateFormat("yyyyMMdd_HHmmss", java.util.Locale.US).format(java.util.Date())
|
||||
}.jpg"
|
||||
val contentValues = android.content.ContentValues().apply {
|
||||
put(android.provider.MediaStore.MediaColumns.DISPLAY_NAME, filename)
|
||||
put(android.provider.MediaStore.MediaColumns.MIME_TYPE, "image/jpeg")
|
||||
put(
|
||||
android.provider.MediaStore.MediaColumns.RELATIVE_PATH,
|
||||
android.os.Environment.DIRECTORY_DCIM + "/PhotonCamera"
|
||||
)
|
||||
}
|
||||
|
||||
val uri = context.contentResolver.insert(
|
||||
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
|
||||
contentValues
|
||||
)
|
||||
|
||||
uri?.let {
|
||||
context.contentResolver.openOutputStream(it)?.use { outputStream ->
|
||||
processedBitmap.compress(Bitmap.CompressFormat.JPEG, 95, outputStream)
|
||||
}
|
||||
}
|
||||
|
||||
processedBitmap.recycle()
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
@@ -796,7 +761,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
override fun onCleared() {
|
||||
super.onCleared()
|
||||
cameraController.release()
|
||||
@@ -804,7 +769,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
lutImageProcessor.release()
|
||||
frameManager.clearCache()
|
||||
shutterSoundPlayer.release()
|
||||
|
||||
|
||||
// 清理 LUT 预览图
|
||||
clearLutPreviews()
|
||||
}
|
||||
|
||||
@@ -616,7 +616,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
return withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val context = getApplication<Application>()
|
||||
val inputStream = context.contentResolver.openInputStream(photo.uri)
|
||||
val inputStream = context.contentResolver.openInputStream(photo.previewUri)
|
||||
val bitmap = BitmapFactory.decodeStream(inputStream)
|
||||
inputStream?.close()
|
||||
|
||||
@@ -631,7 +631,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
showAppBranding = editShowAppBranding
|
||||
)
|
||||
|
||||
photoProcessor.process(context, bitmap, metadata, photo.uri)
|
||||
photoProcessor.process(context, bitmap, metadata, photo.previewUri)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to create preview", e)
|
||||
null
|
||||
@@ -654,7 +654,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val context = getApplication<Application>()
|
||||
val metadata = PhotoMetadata(
|
||||
val metadata = (currentPhotoMetadata ?: PhotoMetadata()).copy(
|
||||
lutId = editLutId,
|
||||
lutIntensity = editLutIntensity,
|
||||
brightness = editBrightness,
|
||||
|
||||
Reference in new issue
Block a user