我能够从我的android库中检索URI的图像,然后使用coil库将其显示在AsyncImage
中。
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
var selectedImageUri by remember { mutableStateOf<Uri?>(null) }
val singlePhotoPikerLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.PickVisualMedia(),
onResult = { uri -> selectedImageUri = uri}
)
RandomAnimalClientTheme {
// A surface container using the 'background' color from the theme
Column (
modifier = Modifier
.fillMaxSize()
.padding(32.dp)
){
Spacer(modifier = Modifier.height(8.dp))
Button(onClick = {
singlePhotoPikerLauncher.launch(
PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)
)
Log.d("URI", selectedImageUri.toString())
}) {
Text(text="Create new animal")
}
AsyncImage(model = selectedImageUri, contentDescription = null )
}
}
}
}
}
我也可以像这样向服务器发送一个多部分请求:
val viewModel: MainViewModel = hiltViewModel()
Button(onClick = {
if(selectedImageUri!=null){
val file = File(cacheDir, "myImage.jpg")
file.createNewFile()
file.outputStream().use{ assets.open("cat.jpg").copyTo(it) }
viewModel.sendNewAnimal(
animalName = "cat",
animalDesc = "a cute mammal",
animalImage = file
)
}
}
) {
Text(text="send new animal")
}
问题是,我不知道如何从应用程序外部发送文件,例如从画廊。如前所述,我只能访问URI。
我已经尝试过像这样将URI转换为实际的File
对象:
val file = File(selectedImageUri.path)
或
val file = selectedImageUri.toFile()
但我会出错。
我该怎么办?
1条答案
按热度按时间xwbd5t1u1#
尝试使用
contentResolver.openInputStream(uri)