如何在Android当中显示网络图片
发布网友
发布时间:2022-04-21 23:17
我来回答
共1个回答
热心网友
时间:2023-06-28 02:29
在android当中显示一张网络图片的时候,其实是比较麻烦的。首先得把这个网络图片转换成java的imputstream流,然后再把这个留转换成一个bitMap.
bitMap是可以作为参数传给imageView的。
在下边的returnBitMap函数是最核心的,也是大家可以重用的,它负责把一个url的网络图片变成一个本地的BitMap。
package com.jinyan.image;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class ActivityMain extends Activity {
/** Called when the activity is first created. */
String imageUrl = "http://i.pbase.com/o6/92/229792/1/80199697.uAs58yHk.50pxCross_of_the_Knights_Templar_svg.png";
Bitmap bmImg;
ImageView imView;
Button button1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imView = (ImageView) findViewById(R.id.imview);
imView.setImageBitmap(returnBitMap(imageUrl));
}
public Bitmap returnBitMap(String url) {
URL myFileUrl = null;
Bitmap bitmap = null;
try {
myFileUrl = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
}