可以利用HttpURLConnection 获取网络上的图片。
列子:
public class HttpURLConnectionActivity extends Activity {
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.simple1);
imageView=(ImageView) this.findViewById(R.id.imageView1);
//传入网络图片地址
try {
URL url = new URL("http://news.xinhuanet.com/photo/2012-02/09/122675973_51n.jpg");
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5*1000);
conn.connect();
InputStream in=conn.getInputStream();
ByteArrayOutputStream bos=new ByteArrayOutputStream();
byte[] buffer=new byte[1024];
int len = 0;
while((len=in.read(buffer))!=-1){
bos.write(buffer,0,len);
}
byte[] dataImage=bos.toByteArray();
bos.close();
in.close();
Bitmap bitmap=BitmapFactory.decodeByteArray(dataImage, 0, dataImage.length);
//Drawable drawable=BitmapDrawable.
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "图片加载失败", 1).show();
}
}
}
|