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

如何在Kotlin中将ImageView的图片以二进制形式传入API接口?

Kotlin实现从ImageView取图并以二进制JPG形式发起API请求

步骤1:从ImageView提取图片并转为JPG字节数组

先从ImageView获取显示的Bitmap,再将其压缩为JPG格式的字节数组:

val imageView: ImageView = findViewById(R.id.your_image_view)
val bitmap = imageView.drawable?.toBitmap() ?: run {
    // 处理ImageView无图片的情况,比如返回空或提示
    Toast.makeText(applicationContext, "ImageView未加载图片", Toast.LENGTH_SHORT).show()
    return@run null
}

// 将Bitmap压缩为JPG字节数组
val outputStream = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, outputStream) // 80为压缩质量(0-100,数值越高画质越好)
val jpgBytes = outputStream.toByteArray()

步骤2:用OkHttp发起POST请求(二进制请求体)

使用OkHttp库发送包含JPG二进制数据的POST请求,先在build.gradle中添加依赖:

dependencies {
    implementation("com.squareup.okhttp3:okhttp:4.12.0")
}

然后编写网络请求代码:

val client = OkHttpClient()

// 构建二进制请求体,指定媒体类型为image/jpeg
val requestBody = RequestBody.create(MediaType.parse("image/jpeg"), jpgBytes)

val request = Request.Builder()
    .url("你的API接口地址")
    .post(requestBody)
    .build()

// 发起异步请求(避免阻塞主线程)
client.newCall(request).enqueue(object : Callback {
    override fun onFailure(call: Call, e: IOException) {
        // 请求失败处理
        runOnUiThread {
            Toast.makeText(applicationContext, "请求失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onResponse(call: Call, response: Response) {
        // 请求成功处理
        runOnUiThread {
            if (response.isSuccessful) {
                val responseContent = response.body?.string()
                Toast.makeText(applicationContext, "上传成功: $responseContent", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(applicationContext, "上传失败,状态码: ${response.code()}", Toast.LENGTH_SHORT).show()
            }
        }
    }
})

关键注意事项

  • 权限配置:在AndroidManifest.xml中添加网络权限:
    <uses-permission android:name="android.permission.INTERNET" />
    
  • 主线程限制:网络请求不能在主线程执行,示例中使用OkHttp的异步回调,回调中更新UI时需通过runOnUiThread切回主线程。
  • 空值处理:必须判断ImageView的drawable是否为空,避免空指针异常。

内容的提问来源于stack exchange,提问作者Lucas Penna

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 01:35:45