Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ interface ProfileRepository {
/** 바뀐 닉네임 저장, 저장된 닉네임 반환 */
suspend fun updateNickname(nickname: String): Result<String>

/** 자른 사진 주소로 업로드 후 프로필 사진 교체, 새 사진 URL 반환 */
/** 자른 사진 파일 주소(file://)로 업로드 후 프로필 사진 교체, 새 사진 URL 반환 */
suspend fun updateProfileImage(imageUri: String): Result<String?>

/** 기본 프로필 이미지로 교체 */
Expand Down
Original file line number Diff line number Diff line change
@@ -1,32 +1,22 @@
package com.routee.android.core.data.member.repository

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import androidx.core.net.toFile
import androidx.core.net.toUri
import com.routee.android.core.common.util.suspendRunCatching
import com.routee.android.core.data.member.exception.MemberException
import com.routee.android.core.data.member.model.MemberProfile
import com.routee.android.core.data.member.remote.dto.request.NicknameUpdateRequest
import com.routee.android.core.data.member.remote.dto.request.ProfileImageUpdateRequest
import com.routee.android.core.data.member.remote.service.MemberService
import com.routee.android.core.data.upload.PresignedImageUploader
import com.routee.android.core.data.upload.UPLOAD_JPEG_QUALITY
import com.routee.android.core.data.upload.remote.dto.request.ImageUrlRequest
import com.routee.android.core.network.exception.ApiException
import com.routee.android.core.network.extension.mapApiException
import com.routee.android.core.network.util.ApiResponseHandler
import dagger.hilt.android.qualifiers.ApplicationContext
import java.io.File
import javax.inject.Inject
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

private const val FILE_PREFIX = "routee_profile_"
private const val FILE_SUFFIX = ".jpg"

internal class ProfileRepositoryImpl @Inject constructor(
@ApplicationContext private val context: Context,
private val memberService: MemberService,
private val uploader: PresignedImageUploader,
private val apiResponseHandler: ApiResponseHandler,
Expand All @@ -43,12 +33,8 @@ internal class ProfileRepositoryImpl @Inject constructor(
.mapApiException(::mapMemberException)

override suspend fun updateProfileImage(imageUri: String): Result<String?> {
val imageFile = suspendRunCatching { createUploadFile(imageUri) }.getOrElse { return Result.failure(it) }
return try {
uploadProfileImage(imageFile).mapApiException(::mapMemberException)
} finally {
imageFile.delete()
}
val imageFile = suspendRunCatching { imageUri.toUri().toFile() }.getOrElse { return Result.failure(it) }
return uploadProfileImage(imageFile).mapApiException(::mapMemberException)
}

override suspend fun resetProfileImage(): Result<Unit> =
Expand All @@ -69,26 +55,6 @@ internal class ProfileRepositoryImpl @Inject constructor(
}.map { it.profileImageUrl }
}

private suspend fun createUploadFile(imageUri: String): File = withContext(Dispatchers.IO) {
val bitmap = context.contentResolver.openInputStream(Uri.parse(imageUri))
?.use(BitmapFactory::decodeStream)
?: error("사진을 읽을 수 없음")
try {
File.createTempFile(FILE_PREFIX, FILE_SUFFIX, context.cacheDir).also { file ->
try {
file.outputStream().use { output ->
check(bitmap.compress(Bitmap.CompressFormat.JPEG, UPLOAD_JPEG_QUALITY, output))
}
} catch (error: Exception) {
file.delete()
throw error
}
}
} finally {
bitmap.recycle()
}
}

private fun mapMemberException(exception: ApiException): Throwable =
if (exception is ApiException.NetworkConnection) {
MemberException.NetworkUnavailable(exception.message)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ internal class WorkoutPhotoLocalDataSource(
File.createTempFile(CAPTURE_PREFIX, IMAGE_SUFFIX, dir)
}

/** 원본을 긴 변 [MAX_EDGE_PX] 이하, 회전 반영해 JPEG 로 압축. 압축 파일 경로 반환 */
/** 원본을 긴 변 [MAX_EDGE_PX] 이하(줄일 때 [MIN_EDGE_PX] 이상 유지), 회전 반영해 JPEG 로 압축. 압축 파일 경로 반환 */
suspend fun compress(
activityId: Long,
photoId: String,
Expand Down Expand Up @@ -78,7 +78,7 @@ internal class WorkoutPhotoLocalDataSource(
check(bounds.outWidth > 0 && bounds.outHeight > 0) { "사진을 읽을 수 없음" }

var sampleSize = 1
while (max(bounds.outWidth, bounds.outHeight) / (sampleSize * 2) >= MAX_EDGE_PX) sampleSize *= 2
while (max(bounds.outWidth, bounds.outHeight) / (sampleSize * 2) >= MIN_EDGE_PX) sampleSize *= 2
val decoded = checkNotNull(
BitmapFactory.decodeFile(file.path, BitmapFactory.Options().apply { inSampleSize = sampleSize }),
) { "사진을 읽을 수 없음" }
Expand All @@ -102,6 +102,7 @@ internal class WorkoutPhotoLocalDataSource(
const val CAPTURE_DIRECTORY = "capture"
const val CAPTURE_PREFIX = "capture_"
const val IMAGE_SUFFIX = ".jpg"
const val MIN_EDGE_PX = 1440
const val MAX_EDGE_PX = 2048
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@ import kotlinx.coroutines.withContext

private const val QUARTER_TURN_DEGREES = 90f
private const val MAX_DECODE_SIZE = 4096
private const val MAX_OUTPUT_SIZE = 2048
private const val OUTPUT_JPEG_QUALITY = 90
private const val CROPPED_FILE_PREFIX = "cropped"
private const val CROPPED_FILE_SUFFIX = ".jpg"
Expand All @@ -85,6 +84,14 @@ private val GuidelineThickness = 1.dp
private val HandleTouchRadius = 24.dp
private val MinBoxSize = 42.dp

/**
* [RouteeImageCropper] 기본값
*/
object RouteeImageCropperDefaults {
/** 자른 이미지 긴 변 최대 px */
const val MAX_OUTPUT_SIZE = 2048
}

/**
* 자르기 영역 비율
*/
Expand Down Expand Up @@ -118,15 +125,15 @@ class RouteeImageCropperState internal constructor(private val cacheDirectory: F
}

/**
* 긴 변 최대 [MAX_OUTPUT_SIZE]px로 잘라 캐시에 저장하고, 성공하면 이전에 자른 파일은 지운다
* 긴 변 최대 [maxOutputSize]px로 잘라 캐시에 저장하고, 성공하면 이전에 자른 파일은 지운다
*/
suspend fun crop(): Result<Uri> = mutex.withLock {
suspend fun crop(maxOutputSize: Int = RouteeImageCropperDefaults.MAX_OUTPUT_SIZE): Result<Uri> = mutex.withLock {
val source = bitmap ?: return Result.failure(IllegalStateException("Image is not loaded"))
val current = geometry ?: return Result.failure(IllegalStateException("Image is not loaded"))
suspendRunCatching {
withContext(Dispatchers.IO) {
val file = File(cacheDirectory, "$CROPPED_FILE_PREFIX${System.currentTimeMillis()}$CROPPED_FILE_SUFFIX")
val cropped = source.cropped(current)
val cropped = source.cropped(current, maxOutputSize)
try {
file.outputStream().use { output ->
check(cropped.compress(Bitmap.CompressFormat.JPEG, OUTPUT_JPEG_QUALITY, output)) {
Expand Down Expand Up @@ -292,11 +299,14 @@ private fun CropGeometry.imageMatrix(image: Bitmap): Matrix = Matrix().apply {
postTranslate(center.x, center.y)
}

private fun Bitmap.cropped(geometry: CropGeometry): Bitmap {
private fun Bitmap.cropped(
geometry: CropGeometry,
maxOutputSize: Int,
): Bitmap {
val box = geometry.box
val sourceWidth = box.width / geometry.scale
val sourceHeight = box.height / geometry.scale
val outputScale = min(1f, MAX_OUTPUT_SIZE / max(sourceWidth, sourceHeight))
val outputScale = min(1f, maxOutputSize / max(sourceWidth, sourceHeight))
val outputWidth = (sourceWidth * outputScale).roundToInt().coerceAtLeast(1)
val outputHeight = (sourceHeight * outputScale).roundToInt().coerceAtLeast(1)
val output = Bitmap.createBitmap(outputWidth, outputHeight, Bitmap.Config.ARGB_8888)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import coil3.SingletonImageLoader
import coil3.request.ImageRequest
import coil3.request.SuccessResult
import coil3.request.allowHardware
import coil3.size.Scale
import coil3.toBitmap
import com.routee.android.core.designsystem.theme.RouteeTheme
import com.routee.android.core.map.model.MapMarker
Expand Down Expand Up @@ -67,6 +68,7 @@ fun rememberPhotoMarkers(photos: List<MapPhoto>): List<MapMarker> {
ImageRequest.Builder(context)
.data(photo.imageUrl)
.size(size)
.scale(Scale.FILL)
.allowHardware(false)
.build(),
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import androidx.compose.ui.tooling.preview.PreviewParameterProvider
import com.routee.android.core.designsystem.component.RouteeBgEllipse
import com.routee.android.core.designsystem.component.RouteeCropAspectRatio
import com.routee.android.core.designsystem.component.RouteeImageCropper
import com.routee.android.core.designsystem.component.RouteeImageCropperDefaults
import com.routee.android.core.designsystem.component.RouteeImageRotationController
import com.routee.android.core.designsystem.component.RouteePageNavBar
import com.routee.android.core.designsystem.component.rememberRouteeImageCropperState
Expand All @@ -45,6 +46,7 @@ import kotlinx.coroutines.launch
* @param onBackClick ◁ 탭 시 호출
* @param onCropComplete 확인 후 자르기에 성공하면 자른 이미지 주소로 호출
* @param onCropFailure 확인 후 자르기에 실패하면 호출
* @param maxOutputSize 자른 이미지 긴 변 최대 px
*/
@Composable
fun RouteeImageCropScreen(
Expand All @@ -54,6 +56,7 @@ fun RouteeImageCropScreen(
onCropComplete: (Uri) -> Unit,
onCropFailure: (Throwable) -> Unit,
modifier: Modifier = Modifier,
maxOutputSize: Int = RouteeImageCropperDefaults.MAX_OUTPUT_SIZE,
) {
val cropperState = rememberRouteeImageCropperState()
val coroutineScope = rememberCoroutineScope()
Expand All @@ -79,7 +82,7 @@ fun RouteeImageCropScreen(
.noRippleClickable(enabled = !isCropping, role = Role.Button) {
isCropping = true
coroutineScope.launch {
cropperState.crop()
cropperState.crop(maxOutputSize)
.onSuccess { currentOnCropComplete(it) }
.onFailure { currentOnCropFailure(it) }
isCropping = false
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import com.routee.android.core.designsystem.component.RouteeCropAspectRatio
import com.routee.android.core.ui.imagecrop.RouteeImageCropScreen
import timber.log.Timber

private const val PROFILE_IMAGE_MAX_SIZE = 640

/**
* 프로필 사진 자르기 (RT-SET-002-4)
*
Expand Down Expand Up @@ -39,5 +41,6 @@ internal fun ProfileImageCropRoute(
onNavigateBack()
},
onCropFailure = { Timber.e(it) },
maxOutputSize = PROFILE_IMAGE_MAX_SIZE,
)
}
Loading