import android.content.ContentValues
import android.content.Context
import android.os.Build
import android.provider.MediaStore
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import coil.compose.AsyncImage
import coil.compose.AsyncImagePainter
import coil.request.ImageRequest
import coil.request.CachePolicy
import java.io.OutputStream

@Composable
fun LoadAndSaveImage() {
    var isLoading by remember { mutableStateOf(true) }
    var loadError by remember { mutableStateOf(false) }
    var requestId by remember { mutableStateOf(0) }
    val data = "https://api.lolimi.cn/API/image-zw/api.php?h=1920"

    val imageRequest = ImageRequest.Builder(LocalContext.current)
        .data(data)
        .memoryCachePolicy(CachePolicy.DISABLED)
        .diskCachePolicy(CachePolicy.DISABLED)
        .setParameter("requestId", requestId)
        .build()

    Column(modifier = Modifier.fillMaxSize()) {
        if (isLoading) {
            CircularProgressIndicator(color = Color.Black)
        } else if (loadError) {
            Text("加载失败,请重试", color = Color.Red, modifier = Modifier.padding(16.dp))
        }

        AsyncImage(
            modifier = Modifier
                .fillMaxSize()
                .clickable { requestId++ },
            model = imageRequest,
            contentDescription = "加载的图片",
            onState = { state ->
                when (state) {
                    is AsyncImagePainter.State.Loading -> {
                        isLoading = true
                    }
                    is AsyncImagePainter.State.Success -> {
                        isLoading = false
                        // 获取位图并保存到相册
                        saveImageToGallery(LocalContext.current, state.result.drawable.toBitmap())
                    }
                    is AsyncImagePainter.State.Error -> {
                        isLoading = false
                        loadError = true
                    }
                    else -> {}
                }
            }
        )
    }
}

fun saveImageToGallery(context: Context, bitmap: Bitmap) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        val resolver = context.contentResolver
        val contentValues = ContentValues().apply {
            put(MediaStore.MediaColumns.DISPLAY_NAME, "Image_${System.currentTimeMillis()}.jpg")
            put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg")
            put(MediaStore.MediaColumns.RELATIVE_PATH, "Pictures/Saved Images")
        }

        val uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
        uri?.let {
            resolver.openOutputStream(it).use { outputStream ->
                if (!bitmap.compress(Bitmap.CompressFormat.JPEG, 95, outputStream)) {
                    throw IOException("无法保存图片")
                }
            }
        }
    } else {
        // 旧版 Android 的保存方法
        // 请根据您的需求实现
    }
}

@Preview(showBackground = true)
@Composable
fun LoadAndSaveImagePreview() {
    LoadAndSaveImage()
}
 

更多推荐