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

如何将GET API返回的image/jpeg数据在ImageView中显示?

解决URLConnection获取JPEG图片并显示在ImageView的问题

你遇到的核心问题是把二进制图片数据当成字符串处理了——image/jpeg返回的是字节流,直接转字符串会因为编码规则破坏原始二进制内容,导致乱码,存文件也会损坏。正确的做法是直接处理字节流,不要转成String。

正确实现步骤:

  • 网络请求必须在子线程执行(Android不允许主线程做网络操作)
  • 直接读取URLConnection的字节输入流,不要转成字符流/字符串
  • 将字节流转换为Bitmap,再切换到主线程更新ImageView

完整代码示例:

首先在Manifest里添加网络权限:

<uses-permission android:name="android.permission.INTERNET" />

Java版本:

// 在Activity或Fragment中调用
new Thread(() -> {
    try {
        URL url = new URL("https://httpbin.org/image/jpeg");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoInput(true);
        
        // 直接获取字节输入流
        InputStream inputStream = connection.getInputStream();
        // 转成Bitmap
        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
        
        // 切换到主线程更新UI
        runOnUiThread(() -> {
            ImageView imageView = findViewById(R.id.your_image_view_id);
            imageView.setImageBitmap(bitmap);
        });
        
        // 关闭流和连接
        inputStream.close();
        connection.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
        // 处理异常,比如显示错误占位图
        runOnUiThread(() -> {
            // imageView.setImageResource(R.drawable.error_placeholder);
        });
    }
}).start();

Kotlin版本:

Thread {
    try {
        val url = URL("https://httpbin.org/image/jpeg")
        val connection = url.openConnection() as HttpURLConnection
        connection.requestMethod = "GET"
        connection.doInput = true
        
        val inputStream = connection.inputStream
        val bitmap = BitmapFactory.decodeStream(inputStream)
        
        runOnUiThread {
            val imageView = findViewById<ImageView>(R.id.your_image_view_id)
            imageView.setImageBitmap(bitmap)
        }
        
        inputStream.close()
        connection.disconnect()
    } catch (e: IOException) {
        e.printStackTrace()
        runOnUiThread {
            // imageView.setImageResource(R.drawable.error_placeholder)
        }
    }
}.start()

关于之前存文件失败的修复:

如果要先存文件再显示,同样要直接写字节流,不能转成字符串。示例代码:

// 在子线程中执行
OutputStream outputStream = new FileOutputStream(new File(getExternalFilesDir(null), "temp.jpg"));
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
    outputStream.write(buffer, 0, len);
}
outputStream.close();
// 之后从文件读取Bitmap
Bitmap bitmap = BitmapFactory.decodeFile(new File(getExternalFilesDir(null), "temp.jpg").getAbsolutePath());

这样就能保证二进制数据不被破坏,不管是直接转Bitmap还是存文件后读取都能正常显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 00:07:21