安卓BitmapFactory.decodeStream()返回null的问题解决方法

本文介绍了解决从网络获取图片并使用BitmapFactory解码时出现null的问题。通过将InputStream转换为byte数组,再使用decodeByteArray方法进行解码,成功生成Bitmap对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述:

从网络获取图片,数据为InputStream流对象,然后调用BitmapFactory的decodeStream()方法解码获取图片,返回null。

代码如下:

private Bitmap getUrlBitmap(String url) {  
    Bitmap bm;  
    try {  
        URL imageUrl = new URL(url);  
        InputStream is = imageUrl .openStream();  
        bm = BitmapFactory.decodeStream(is); // 如果采用这种解码方式在低版本的API上会出现解码问题  
        is.close();  
        return bm;  
    } catch (MalformedURLException e) {  
        e.printStackTrace();  
    } catch (IOException e) {  
        e.printStackTrace();  
    }  
    return null;  
  
}  

解决办法:定义一个根据图片url获取InputStream的方法

 
    public static byte[] getBytes(InputStream is) throws IOException {  
        ByteArrayOutputStream outstream = new ByteArrayOutputStream();  
        byte[] buffer = new byte[1024]; // 用数据装  
        int len = -1;  
        while ((len = is.read(buffer)) != -1) {  
            outstream.write(buffer, 0, len);  
        }  
        outstream.close();   // 关闭流一定要记得。  

        return outstream.toByteArray();  
    }  

然后使用方法decodeByteArray()方法解析编码,生成Bitmap对象

 byte[] data = getBytesFromInputStream(new URL(imgUrl).openStream());  
 Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);

 

转载于:https://www.cnblogs.com/butterfly-clover/p/4699484.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值