• 转载 Android中使用BitmapFactory的decodeStream()方法解码图片失败问题


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


    private Bitmap getUrlBitmap(String url)
    {
    Bitmap bm;
    try{
    URL imageUrl
    =new URL(url);
    HttpURLConnection conn
    =(HttpURLConnection)imageUrl.openConnection();
    conn.connect();
    InputStream is
    =conn.getInputStream();
    //byte[] bt=getBytes(is); //注释部分换用另外一种方式解码
    //bm=BitmapFactory.decodeByteArray(bt,0,bt.length);
    bm=BitmapFactory.decodeStream(is); //如果采用这种解码方式在低版本的API上会出现解码问题
    is.close();
    conn.disconnect();
    return bm;
    }
    catch(MalformedURLException e)
    {
    e.printStackTrace();
    }
    catch (IOException e)
    {
    e.printStackTrace();
    }
    return null;

    }

    结果在运行时编译器提示: DEBUG
    /skia(xxx): --- decoder->decode returned false

    已经确定从网络获取的数据流没有出现问题,而是在图片解码时出现错误。上网查找了不少资料,也没有得出确切的原因,不过有几条意见值得关注。

    一种说法是在android 较低版本的api中会有不少内部的错误,我的代码运行时选择2.1API Level 7和2.2API Level 8都会出现这个问题,而选择2.
    3 API Level 9后能够正常解码图片。

    我的另外一种做法是换用别的解码方式对图片解码,见代码中被注释的那俩行,使用decodeByteArray()方法在低版本的API上也能够正常解码,解决了这个问题。

    其中getBytes(InputStream is)是将InputStream对象转换为Byte[]的方法,具体代码如下:

    private byte[] getBytes(InputStream is) throws IOException {

    ByteArrayOutputStream baos
    = new ByteArrayOutputStream();
    byte[] b = new byte[1024];
    int len = 0;

    while ((len = is.read(b, 0, 1024)) != -1)
    {
    baos.write(b,
    0, len);
    baos.flush();
    }
    byte[] bytes = baos.toByteArray();
    return bytes;
    }
  • 相关阅读:
    网络嗅探器
    struct udphdr
    struct tcphdr
    struct iphdr
    socket函数
    SQL SERVER-解析Extendevent文件数据
    SQL SERVER-日期按时区转换
    SQL SERVER-CROSS APPLY
    WinServer-文件共享端口
    SQL SERVER-修改实例的排序规则
  • 原文地址:https://www.cnblogs.com/xiao0/p/2174446.html
Copyright © 2020-2023  润新知