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

Kotlin中如何将Microsoft Graph API返回的二进制图片转为Bitmap

解决Microsoft Graph API获取照片转Bitmap为null的问题

问题根源

你代码里的response.body?.charStream()?.readText()?.let { ... }是核心错误:

  • 图片是二进制数据,用字符流读取会破坏原始字节结构,导致数据损坏
  • 调用readText()会一次性耗尽响应体的流,后续再调用byteStream()时,流已经没有数据可读,BitmapFactory自然返回null

修正步骤

  1. 彻底移除所有处理字符流的代码(charStream()、readText()相关逻辑)
  2. 直接从响应体获取字节流转换Bitmap
  3. 注意:OkHttp的回调运行在子线程,必须切换到主线程更新ImageView

修正后的完整代码

try {
    val client = OkHttpClient()
    val request: Request = Request.Builder()
        .url("https://graph.microsoft.com/v1.0/users/{UPN}/photo/\$value")
        .get()
        .addHeader("Authorization", token)
        .build()

    client.newCall(request).enqueue(object : Callback {
        override fun onFailure(call: Call, e: IOException) {
            e.printStackTrace()
            Log.d("ProfilePhoto", "请求失败: ${e.message}")
        }

        override fun onResponse(call: Call, response: Response) {
            response.use {
                if (!response.isSuccessful) {
                    Log.d("ProfilePhoto", "请求失败: $response")
                    return
                }

                // 直接读取字节流,不提前消耗响应体
                val inputStream = response.body?.byteStream() ?: return
                val bitmap = BitmapFactory.decodeStream(inputStream)

                // 切换到主线程更新UI
                runOnUiThread {
                    if (bitmap != null) {
                        yourImageView.setImageBitmap(bitmap)
                        Log.d("ProfilePhoto", "Bitmap转换成功")
                    } else {
                        Log.d("ProfilePhoto", "Bitmap转换失败,数据可能损坏")
                    }
                }
            }
        }
    })
} catch (err: Exception) {
    Log.d("ProfilePhoto", "异常: ${err.message}")
}

额外优化点

  • GET请求无需设置Content-Type请求头,该头用于标识请求体类型,GET无请求体,可直接删除
  • URL中的$value用反斜杠转义即可,无需拼接字符串
  • 使用response.use自动关闭响应体,避免资源泄漏
  • 异常捕获改用Exception,比Error更贴合业务场景(Error通常指系统级严重错误)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 19:54:39