Android 网络图片查看显示的实现方法
我们的应用或多或少都会从网络获取图片数据然后进行显示,下面就将实现一个这样的例子,获取网络中的图片!
首先:我们来看一下效果图
界面中有三个控件,一个edittext,一个button,一个imageview
1、下面是具体布局文件
<edittext
android:id="@+id/picturepagh"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<button
android:id="@+id/btn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="查看" />
<imagebutton
android:id="@+id/imageview"
android:layout_width="fill_parent"
android:layout_height="200px" />
2、在mainactivity中进行图片图示代码编写
public class mainactivity extends activity {
private button btn;
private edittext path;
private imageview imgview;
@override
protected void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.activity_main);
btn = (button) findviewbyid(r.id.btn);
path = (edittext) findviewbyid(r.id.picturepagh);
imgview = (imageview) findviewbyid(r.id.imageview);
btn.setonclicklistener(new onclicklistener() {
@override
public void onclick(view v) {
log.i("click", ((button) v).gettext().tostring());
new thread(runa).start();
}
});
}
public void setview() {
string picturepath = path.gettext().tostring();
byte[] data = null;
try {
data = imageservice.getimage(picturepath);
bitmap bitmap = bitmapfactory.decodebytearray(data, 0, data.length);// bitmapfactory:图片工厂!
looper.prepare();// 必须调用此方法,要不然会报错
message msg = new message();
msg.what = 0;
msg.obj = bitmap;
handler.sendmessage(msg);
} catch (exception e) {
toast.maketext(getapplicationcontext(), "获取图片错误", 1).show();
}
}
private handler handler = new handler() {
@override
public void handlemessage(message msg) {
if (msg.what == 0) {
updateimageview((bitmap) msg.obj);
}
}
};
private runnable runa = new runnable() {
@override
public void run() {
setview();
}
};
private void updateimageview(bitmap bm) {
imgview.setimagebitmap(bm);
}
}
3、添加一个imageservice图片服务类,里面包含一个获取网络数据的方法;
public class imageservice {
// 获取网络图片的数据
public static byte[] getimage(string picturepath) throws exception {
url url = new url(picturepath);
httpurlconnection conn = (httpurlconnection) url.openconnection();// 基于http协议的连接对象
conn.setconnecttimeout(10);// 10秒;
conn.setrequestmethod("get");// 大写
if (conn.getresponsecode() == 200) {
inputstream ins = conn.getinputstream();
return streamtool.read(ins);
}
return null;
}
}
4、添加一个流处理工作类streamtool
public class streamtool {
public static byte[] read(inputstream ins) throws exception {
bytearrayoutputstream outstream = new bytearrayoutputstream();
byte[] buffer = new byte[1024];
int length = 0;
while ((length = ins.read(buffer)) > -1) {
outstream.write(buffer, 0, length);
}
outstream.close();
return outstream.tobytearray();
}
}
5、大功告成?no,还要添加网络访问权限: <uses-permission android:name="android.permission.internet" />
ok,运行程序!