我正在尝试从StaticConfig.getMyUser().getAvatar()
的网址获取位图。网址如下"https://lh6.googleusercontent.com/-0feEeEohl8I/AAAAAAAAAAI/AAAAAAAAAGA/htLteFBdk5M/s96-c/photo.jpg"
。
当我使用下面的代码时,src
为空。我不知道为什么。我目前正在调查this link,但我仍然对我应该做的事情一无所知。
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
}
答案 0 :(得分:0)
答案 1 :(得分:0)
正如其他人所建议的那样,理想的方法是使用Picasso或Glide。
因为它可以处理很多事情,从缓存到内存优化。 例如。有了Glide,你只需要写
Glide.with(context)
.load("https://lh6.googleusercontent.com/-0feEeEohl8I/AAAAAAAAAAI/AAAAAAAAAGA/htLteFBdk5M/s96-c/photo.jpg")
.into(imgview);
或者如果您想手动编写,可以使用以下方法。 imageview 是初始化的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许可。
答案 2 :(得分:0)
以防您想使用kotlin版本。
class SetBitmapFromNetwork(img: ImageView?): AsyncTask<Void, Void, Bitmap>() {
var img:ImageView? = img
override fun doInBackground(vararg p0: Void?): Bitmap {
val conn: HttpURLConnection = (URL("https://lh6.googleusercontent.com/-0feEeEohl8I/AAAAAAAAAAI/AAAAAAAAAGA/htLteFBdk5M/s96-c/photo.jpg").openConnection()) as HttpURLConnection
conn.doInput = true
val ism: InputStream = conn.inputStream
return BitmapFactory.decodeStream(ism)
}
override fun onPostExecute(result: Bitmap?) {
super.onPostExecute(result)
img?.setImageBitmap(result)
}
}
请致电,
SetBitmapFromNetwork(img).execute()