feat: heic support

This commit is contained in:
zhoubinjia committed 2026-06-08 11:35:54 +08:00
1 parent e12dc81103
commit 864faf485b
11 files changed
+281 -6

No files matched your search

+3
View File
@@ -169,6 +169,9 @@ dependencies {
// ExifInterface for writing EXIF metadata
implementation(libs.androidx.exifinterface)
// HEIC export through the platform image encoder
implementation(libs.androidx.heifwriter)
// DataStore for user preferences
implementation("androidx.datastore:datastore-preferences:1.0.0")
@@ -129,6 +129,7 @@ data class UserPreferences(
val useMFSR: Boolean = false, // 是否启用 RAW 多帧超分
val superResolutionScale: Float = 1.5f, // RAW 多帧超分倍率
val photoQuality: Int = 95, // 照片质量: 90, 95, 100
val useHeicExport: Boolean = false, // 是否优先使用 HEIC 导出
val useLivePhoto: Boolean = false, // 是否启用 Live Photo (Motion Photo)
val enableDevelopAnimation: Boolean = false, // 是否启用拍摄后的显影动画
val backgroundImage: String = "camera_bg", // 背景图资源名或文件路径
@@ -285,6 +286,7 @@ class UserPreferencesRepository(private val context: Context) {
private val USE_SUPER_RESOLUTION = booleanPreferencesKey("use_super_resolution")
private val RAW_SUPER_RESOLUTION_SCALE = floatPreferencesKey("raw_super_resolution_scale")
private val PHOTO_QUALITY = intPreferencesKey("photo_quality")
private val USE_HEIC_EXPORT = booleanPreferencesKey("use_heic_export")
private val USE_LIVE_PHOTO = booleanPreferencesKey("use_live_photo")
private val ENABLE_DEVELOP_ANIMATION = booleanPreferencesKey("enable_develop_animation")
private val BACKGROUND_IMAGE = stringPreferencesKey("background_image")
@@ -422,6 +424,7 @@ class UserPreferencesRepository(private val context: Context) {
useMFSR = preferences[USE_SUPER_RESOLUTION] ?: false,
superResolutionScale = preferences[RAW_SUPER_RESOLUTION_SCALE] ?: 1.5f,
photoQuality = preferences[PHOTO_QUALITY] ?: 95,
useHeicExport = preferences[USE_HEIC_EXPORT] ?: false,
useLivePhoto = preferences[USE_LIVE_PHOTO] ?: false,
enableDevelopAnimation = preferences[ENABLE_DEVELOP_ANIMATION] ?: false,
backgroundImage = preferences[BACKGROUND_IMAGE] ?: "camera_bg",
@@ -1161,6 +1164,12 @@ class UserPreferencesRepository(private val context: Context) {
}
}
suspend fun saveUseHeicExport(enabled: Boolean) {
context.dataStore.edit { preferences ->
preferences[USE_HEIC_EXPORT] = enabled
}
}
/**
* 保存是否启用 Live Photo
*/
@@ -1,5 +1,6 @@
package com.hinnka.mycamera.gallery
import android.graphics.Bitmap
import androidx.exifinterface.media.ExifInterface
import com.hinnka.mycamera.camera.CaptureInfo
import com.hinnka.mycamera.utils.PLog
@@ -65,6 +66,57 @@ object ExifWriter {
}
}
fun buildExifBlock(cacheDir: File, captureInfo: CaptureInfo): ByteArray? {
val tempFile = File(cacheDir, "temp_exif_${System.nanoTime()}.jpg")
return try {
val bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888)
try {
tempFile.outputStream().use { output ->
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, output)
}
} finally {
bitmap.recycle()
}
writeExif(tempFile, captureInfo)
extractJpegExifBlock(tempFile.readBytes())
} catch (e: Exception) {
PLog.e(TAG, "Failed to build EXIF block", e)
null
} finally {
tempFile.delete()
}
}
private fun extractJpegExifBlock(jpegBytes: ByteArray): ByteArray? {
var offset = 2
if (jpegBytes.size < offset || jpegBytes[0] != 0xFF.toByte() || jpegBytes[1] != 0xD8.toByte()) {
return null
}
while (offset + 4 <= jpegBytes.size) {
if (jpegBytes[offset] != 0xFF.toByte()) return null
val marker = jpegBytes[offset + 1].toInt() and 0xFF
if (marker == 0xDA || marker == 0xD9) return null
val segmentLength = ((jpegBytes[offset + 2].toInt() and 0xFF) shl 8) or
(jpegBytes[offset + 3].toInt() and 0xFF)
if (segmentLength < 2 || offset + 2 + segmentLength > jpegBytes.size) return null
val payloadOffset = offset + 4
val payloadLength = segmentLength - 2
if (marker == 0xE1 && payloadLength >= EXIF_HEADER.size) {
val hasExifHeader = EXIF_HEADER.indices.all { index ->
jpegBytes[payloadOffset + index] == EXIF_HEADER[index]
}
if (hasExifHeader) {
return jpegBytes.copyOfRange(payloadOffset, payloadOffset + payloadLength)
}
}
offset += 2 + segmentLength
}
return null
}
/**
* 核心写入逻辑
*/
@@ -198,4 +250,13 @@ object ExifWriter {
}
return if (x == 0) 1 else x
}
private val EXIF_HEADER = byteArrayOf(
'E'.code.toByte(),
'x'.code.toByte(),
'i'.code.toByte(),
'f'.code.toByte(),
0,
0
)
}
@@ -536,11 +536,16 @@ object GalleryManager {
suffix: String? = null,
preparedUltraHdrSource: GainmapSourceSet? = null,
preparedGainmapResult: GainmapResult? = null,
preferHeicExport: Boolean? = null,
): Boolean {
return withContext(Dispatchers.IO) {
val tempExportFile = File(context.cacheDir, "temp_export_${System.nanoTime()}.jpg")
try {
if (bitmap == null && canReuseEmbeddedGainmap(metadata)) {
val shouldPreferHeic = preferHeicExport
?: (ContentRepository.getInstance(context).userPreferencesRepository.userPreferences.firstOrNull()
?.useHeicExport ?: false)
if (!shouldPreferHeic && bitmap == null && canReuseEmbeddedGainmap(metadata)) {
val embeddedBitmap = loadOriginalBitmap(context, id)
if (embeddedBitmap != null && hasBitmapGainmap(embeddedBitmap)) {
PLog.d(TAG, "Reusing embedded gainmap for export: $id")
@@ -608,6 +613,9 @@ object GalleryManager {
"processedBitmap = ${processedBitmap.colorSpace?.name}, ultraHdrSource=${ultraHdrSource?.sourceKind}, gainmap=${gainmapResult != null}"
)
val videoFile = File(getPhotoDir(context, id), VIDEO_FILE)
val isLivePhoto = videoFile.exists()
// 保存到指定目录
val date = metadata.dateTaken ?: System.currentTimeMillis()
@@ -618,8 +626,29 @@ object GalleryManager {
withSuffix += ".$lutName"
}
val filename =
"PhotonCamera_${SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date(date))}$withSuffix.jpg"
val baseFilename =
"PhotonCamera_${SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date(date))}$withSuffix"
if (shouldPreferHeic && !isLivePhoto) {
val heicExported = exportEncodedPhotoToMediaStore(
context = context,
id = id,
bitmap = processedBitmap,
metadata = metadata,
photoQuality = photoQuality,
baseFilename = baseFilename,
extension = HeicExportEncoder.EXTENSION,
mimeType = HeicExportEncoder.MIME_TYPE,
gainmapResult = gainmapResult
)
if (heicExported) {
processedBitmap.recycle()
return@withContext true
}
PLog.w(TAG, "HEIC export unavailable or failed, falling back to JPEG for photo $id")
}
val filename = "$baseFilename.jpg"
val contentValues = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, filename)
put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg")
@@ -632,9 +661,6 @@ object GalleryManager {
)
uri?.let {
val videoFile = File(getPhotoDir(context, id), VIDEO_FILE)
val isLivePhoto = videoFile.exists()
val exportWriteElapsed = measureTimeMillis {
FileOutputStream(tempExportFile).use { outputStream ->
writeFinalJpeg(
@@ -835,6 +861,70 @@ object GalleryManager {
}
}
private suspend fun exportEncodedPhotoToMediaStore(
context: Context,
id: String,
bitmap: Bitmap,
metadata: MediaMetadata,
photoQuality: Int,
baseFilename: String,
extension: String,
mimeType: String,
gainmapResult: GainmapResult? = null,
): Boolean {
val tempExportFile = File(context.cacheDir, "temp_export_${System.nanoTime()}.$extension")
try {
val captureInfo = metadata.toCaptureInfo().copy(
imageWidth = bitmap.width,
imageHeight = bitmap.height
)
val exifData = if (mimeType == HeicExportEncoder.MIME_TYPE) {
ExifWriter.buildExifBlock(context.cacheDir, captureInfo) ?: return false
} else {
null
}
val encoded = when (mimeType) {
HeicExportEncoder.MIME_TYPE -> HeicExportEncoder.write(
bitmap = bitmap,
outputFile = tempExportFile,
quality = photoQuality,
gainmapResult = gainmapResult,
exifData = exifData
)
else -> false
}
if (!encoded) return false
val filename = "$baseFilename.$extension"
val contentValues = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, filename)
put(MediaStore.MediaColumns.MIME_TYPE, mimeType)
put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM + "/PhotonCamera")
}
val uri = context.contentResolver.insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
contentValues
) ?: return false
context.contentResolver.openOutputStream(uri)?.use { output ->
tempExportFile.inputStream().use { input -> input.copyTo(output) }
} ?: return false
updateMetadata(context, id) { current ->
current.copy(
exportedUris = current.exportedUris + uri.toString()
)
}
PLog.d(TAG, "Exported $mimeType URI saved: $uri for photo $id")
return true
} catch (e: Exception) {
PLog.w(TAG, "Failed to export encoded photo as $mimeType", e)
return false
} finally {
tempExportFile.delete()
}
}
suspend fun exportDng(context: Context, photoId: String, data: ByteArray, metadata: MediaMetadata) =
withContext(Dispatchers.IO) {
try {
@@ -0,0 +1,80 @@
package com.hinnka.mycamera.gallery
import android.graphics.Bitmap
import android.media.MediaCodecList
import android.media.MediaFormat
import android.os.Build
import androidx.heifwriter.HeifWriter
import com.hinnka.mycamera.hdr.GainmapResult
import com.hinnka.mycamera.utils.PLog
import java.io.File
object HeicExportEncoder {
private const val TAG = "HeicExportEncoder"
const val MIME_TYPE = "image/heic"
const val EXTENSION = "heic"
private const val ENCODE_TIMEOUT_MS = 10_000L
val isSupported: Boolean
by lazy { hasHeicEncoder() }
private fun hasHeicEncoder(): Boolean {
return runCatching {
MediaCodecList(MediaCodecList.REGULAR_CODECS).codecInfos.any { codecInfo ->
codecInfo.isEncoder && codecInfo.supportedTypes.any { type ->
type.equals(MediaFormat.MIMETYPE_IMAGE_ANDROID_HEIC, ignoreCase = true)
}
}
}.getOrElse { error ->
PLog.w(TAG, "HEIC encoder capability check failed: ${error.message}")
false
}
}
fun write(
bitmap: Bitmap,
outputFile: File,
quality: Int,
gainmapResult: GainmapResult? = null,
exifData: ByteArray? = null,
): Boolean {
if (!isSupported) return false
return runCatching {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE && gainmapResult != null) {
bitmap.gainmap = gainmapResult.gainmap
}
HeifWriter.Builder(
outputFile.absolutePath,
bitmap.width,
bitmap.height,
HeifWriter.INPUT_MODE_BITMAP
)
.setQuality(quality.coerceIn(0, 100))
.setMaxImages(1)
.setPrimaryIndex(0)
.setGridEnabled(true)
.build()
.use { writer ->
writer.start()
if (exifData != null) {
writer.addExifData(0, exifData, 0, exifData.size)
}
writer.addBitmap(bitmap)
writer.stop(ENCODE_TIMEOUT_MS)
}
val success = outputFile.exists() && outputFile.length() > 0L
PLog.d(
TAG,
"HEIC export encode result=$success, size=${bitmap.width}x${bitmap.height}, gainmap=${gainmapResult != null}, exif=${exifData != null}, bytes=${outputFile.length()}"
)
success
}.getOrElse { error ->
PLog.w(TAG, "HEIC export encode failed: ${error.message}")
outputFile.delete()
false
}
}
}
@@ -107,6 +107,7 @@ import com.hinnka.mycamera.camera.MultiFrameConfig
import com.hinnka.mycamera.data.AiFocusTargetMode
import com.hinnka.mycamera.data.VolumeKeyAction
import com.hinnka.mycamera.frame.FrameInfo
import com.hinnka.mycamera.gallery.HeicExportEncoder
import com.hinnka.mycamera.lut.BaselineColorCorrectionTarget
import com.hinnka.mycamera.lut.LutInfo
import com.hinnka.mycamera.lut.creator.OpenAIApiClient
@@ -215,6 +216,7 @@ fun SettingsScreen(
val useLivePhoto by viewModel.useLivePhoto.collectAsState()
val enableDevelopAnimation by viewModel.enableDevelopAnimation.collectAsState()
val photoQuality by viewModel.photoQuality.collectAsState(initial = 95)
val useHeicExport by viewModel.useHeicExport.collectAsState(initial = false)
val tonemapMode by viewModel.tonemapMode.collectAsState()
val fixTonemapPreview by viewModel.fixTonemapPreview.collectAsState()
val useGpuAcceleration by viewModel.useGpuAcceleration.collectAsState()
@@ -291,6 +293,7 @@ fun SettingsScreen(
val context = androidx.compose.ui.platform.LocalContext.current
val coroutineScope = androidx.compose.runtime.rememberCoroutineScope()
val isHdrSettingsSupported = remember { Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE && !DeviceUtil.isHarmonyOS }
val isHeicExportSupported = remember { HeicExportEncoder.isSupported }
val backupLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.CreateDocument("application/zip")
@@ -919,6 +922,20 @@ fun SettingsScreen(
onLevelSelected = { viewModel.setPhotoQuality(it) }
)
if (isHeicExportSupported) {
HorizontalDivider(
color = Color.White.copy(alpha = 0.1f),
modifier = Modifier.padding(vertical = 8.dp)
)
SwitchSettingItem(
title = stringResource(R.string.settings_use_heic_export),
description = stringResource(R.string.settings_use_heic_export_description),
checked = useHeicExport,
onCheckedChange = { viewModel.setUseHeicExport(it) }
)
}
HorizontalDivider(
color = Color.White.copy(alpha = 0.1f),
modifier = Modifier.padding(vertical = 8.dp)
@@ -781,6 +781,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
}
.stateIn(viewModelScope, SharingStarted.Eagerly, null)
val photoQuality: Flow<Int> = userPreferencesRepository.userPreferences.map { it.photoQuality }
val useHeicExport: Flow<Boolean> = userPreferencesRepository.userPreferences.map { it.useHeicExport }
val defaultFocalLength: Flow<Float> = userPreferencesRepository.userPreferences.map { it.defaultFocalLength }
val customFocalLengths: Flow<List<Float>> = userPreferencesRepository.userPreferences.map { it.customFocalLengths }
@@ -3415,6 +3416,12 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
}
}
fun setUseHeicExport(enabled: Boolean) {
viewModelScope.launch {
userPreferencesRepository.saveUseHeicExport(enabled)
}
}
/**
* 设置锐化强度
*/
@@ -250,6 +250,8 @@
<string name="settings_detail_enhancement_description">手动微调锐化和降噪参数</string>
<string name="settings_photo_quality">照片质量</string>
<string name="settings_photo_quality_description">选择 JPEG 压缩的照片质量(越高画质越好,但文件体积也越大)</string>
<string name="settings_use_heic_export">HEIC 导出</string>
<string name="settings_use_heic_export_description">在支持的设备上优先使用原生 HEIC 导出。</string>
<string name="settings_tonemap_mode">色调映射</string>
<string name="settings_tonemap_mode_description">调整硬件色调映射(对比度/伽马)模式</string>
<string name="settings_tonemap_mode_fast">快速</string>
@@ -164,6 +164,8 @@
<string name="settings_detail_enhancement_description">手動微調銳化和降噪參數</string>
<string name="settings_photo_quality">相片品質</string>
<string name="settings_photo_quality_description">選擇 JPEG 壓縮的相片品質(越高畫質越好,但檔案體積也越大)</string>
<string name="settings_use_heic_export">HEIC 匯出</string>
<string name="settings_use_heic_export_description">在支援的裝置上優先使用原生 HEIC 匯出。</string>
<string name="settings_tonemap_mode">色調映射</string>
<string name="settings_tonemap_mode_description">調整硬體色調映射(對比度/伽馬)模式</string>
<string name="settings_tonemap_mode_fast">快速</string>
+2
View File
@@ -252,6 +252,8 @@
<string name="settings_detail_enhancement_description">Fine-tune sharpening and noise reduction parameters</string>
<string name="settings_photo_quality">Photo Quality</string>
<string name="settings_photo_quality_description">Select the JPEG compression quality for photos (higher = better quality, larger file size)</string>
<string name="settings_use_heic_export">HEIC Export</string>
<string name="settings_use_heic_export_description">Prefer native HEIC export on supported devices.</string>
<string name="settings_tonemap_mode">Tone Mapping</string>
<string name="settings_tonemap_mode_description">Adjust the hardware tone mapping (contrast/gamma) mode</string>
<string name="settings_tonemap_mode_fast">Fast</string>
+2
View File
@@ -13,6 +13,7 @@ materialIconsExtended = "1.7.8"
coil = "2.7.0"
navigationCompose = "2.9.6"
exifinterface = "1.4.2"
heifwriter = "1.1.0"
billing = "8.3.0"
fragment = "1.8.9"
media3 = "1.10.0"
@@ -54,6 +55,7 @@ androidx-material-icons-extended = { group = "androidx.compose.material", name =
coil-compose = { group = "io.coil-kt", name = "coil-compose", version.ref = "coil" }
androidx-navigation-compose = { group = "androidx.navigation", name = "navigation-compose", version.ref = "navigationCompose" }
androidx-exifinterface = { group = "androidx.exifinterface", name = "exifinterface", version.ref = "exifinterface" }
androidx-heifwriter = { group = "androidx.heifwriter", name = "heifwriter", version.ref = "heifwriter" }
androidx-fragment-ktx = { group = "androidx.fragment", name = "fragment-ktx", version.ref = "fragment" }
androidx-animation-core = { group = "androidx.compose.animation", name = "animation-core", version.ref = "animationCore" }
androidx-lifecycle-process = { group = "androidx.lifecycle", name = "lifecycle-process", version.ref = "lifecycleProcess" }