You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Amazon Rekognition的DetectLabelsRequest传入图片URL完成标签检测

修正方案

你的原有代码存在3个核心错误:

  • FileInputStream 只能读取本地文件路径,无法直接加载公网HTTP URL的资源
  • 没有实际读取URL对应的图片二进制内容,只分配了空的ByteBuffer,传入的图片数据无效
  • 网络请求和AWS服务调用不能放在安卓主线程执行,会触发ANR异常,且硬编码明文AKSK到客户端代码存在严重泄露风险

修正后可运行代码

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.amazonaws.auth.BasicAWSCredentials
import com.amazonaws.services.rekognition.AmazonRekognitionClient
import com.amazonaws.services.rekognition.model.DetectLabelsRequest
import com.amazonaws.services.rekognition.model.Image
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.net.URL
import java.nio.ByteBuffer

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // 放在协程后台线程执行,避免阻塞主线程
        lifecycleScope.launch {
            val labels = detectImageLabels("http://placehold.it/120x120&text=image1")
            // 回到主线程处理检测结果
            labels?.forEach { label ->
                println("检测标签:${label.name}, 置信度:${label.confidence}")
            }
        }
    }

    private suspend fun detectImageLabels(imageUrl: String): List<com.amazonaws.services.rekognition.model.Label>? = withContext(Dispatchers.IO) {
        return@withContext try {
            // 初始化Rekognition客户端(正式环境不要硬编码AKSK,建议通过AWS Cognito获取临时凭证)
            val rekognitionClient = AmazonRekognitionClient(
                BasicAWSCredentials("你的AccessKey", "你的SecretKey")
            ).apply {
                setEndpoint("rekognition.你开通服务的AWS区域.amazonaws.com") // 示例:rekognition.us-east-1.amazonaws.com
            }

            // 下载网络图片到字节数组
            val url = URL(imageUrl)
            val imageBytes = url.openStream().use { it.readBytes() }

            // 构造Rekognition要求的Image对象
            val rekognitionImage = Image().withBytes(ByteBuffer.wrap(imageBytes))

            // 构造检测请求
            val request = DetectLabelsRequest()
                .withImage(rekognitionImage)
                .withMaxLabels(10)
                .withMinConfidence(75f)

            // 执行检测返回标签结果
            val result = rekognitionClient.detectLabels(request)
            result.labels
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }
}

额外配置注意事项

  • 需要在AndroidManifest.xml中添加网络权限:<uses-permission android:name="android.permission.INTERNET" />
  • Rekognition对字节流传入的图片大小限制为最大15MB,超出限制的图片需要先压缩再提交检测
  • 必须替换代码中的AWS区域为你实际开通服务的区域,否则会请求失败

内容的提问来源于stack exchange,提问作者Rob Aberan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 09:54:02