BitmapFactory返回空位图 [英] BitmapFactory returning null Bitmap

查看:87
本文介绍了BitmapFactory返回空位图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从StaticConfig.getMyUser().getAvatar()的URL获取位图.网址如下"https://lh6.googleusercontent.com/-0feEeEohl8I/AAAAAAAAAAI/AAAAAAAAAGA/htLteFBdk5M/s96-c/photo.jpg".

I am trying to get the Bitmap from a URL from the StaticConfig.getMyUser().getAvatar(). The url is as follows "https://lh6.googleusercontent.com/-0feEeEohl8I/AAAAAAAAAAI/AAAAAAAAAGA/htLteFBdk5M/s96-c/photo.jpg".

当我使用下面的代码时,src为空.我不知道为什么.我目前正在研究此链接,但是我仍然不知道应该怎么做.

When I use the code below, src is null. I'm not sure why. I am currently looking into this link but I'm still clueless to what I should do.

private void setImageAvatar(Context context){
    Resources res = getResources();
    Bitmap src;
    byte[] decodedString = Base64.decode(StaticConfig.getMyUser().getAvatar(), Base64.DEFAULT);
    src = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
    if(src == null){
        Log.e("UserProf","src is null");
    }
    // code to do something with src here
}

推荐答案

其他人建议,理想的方法是使用滑行.

As suggested by others, the ideal way would be to use Picasso or Glide.

因为它为您处理了很多事情,从缓存到内存优化. 例如使用Glide,您只需要编写

Because it handles many things, from caching to memory optimisation for you. for eg. with Glide you will just have to write

Glide.with(context)
     .load("https://lh6.googleusercontent.com/-0feEeEohl8I/AAAAAAAAAAI/AAAAAAAAAGA/htLteFBdk5M/s96-c/photo.jpg")
     .into(imgview);

或者如果要手动编写,则可以使用以下方法. imageview 是已初始化Imageview的实例.

Or If you want to write manually, you can use below method. imageview is instance of initialized Imageview.

public void setBitmapFromNetwork(){

Runnable runnable = new Runnable() {
    Bitmap bitmap = null;

    @Override
    public void run() {
        try {
            bitmap = getBitmapFromLink();
        } catch (IOException e) {
            e.printStackTrace();
        }
        imageview.post(new Runnable() {
            @Override
            public void run() {
                imageview.setImageBitmap(bitmap);
        }});
    }};
    new Thread(runnable).start();
}


public Bitmap getBitmapFromLink() throws IOException{
    HttpURLConnection conn =(HttpURLConnection) new URL("https://lh6.googleusercontent.com/-0feEeEohl8I/AAAAAAAAAAI/AAAAAAAAAGA/htLteFBdk5M/s96-c/photo.jpg").openConnection());
    conn.setDoInput(true);
    InputStream ism = conn.getInputStream();
    Bitmap bitmap = BitmapFactory.decodeStream(ism);
    if (ism != null) {
        ism .close();
    }
    return bitmap;
}

并且请确保您已在清单中授予Internet权限.

And please make sure you have given Internet permission in manifest.

这篇关于BitmapFactory返回空位图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆