你的位置:首页 > 操作系统

[操作系统]从网上加载图片然后展示在屏幕上


直接上代码

 1 package org.lxh.server; 2  3 import java.io.ByteArrayOutputStream; 4 import java.io.InputStream; 5 import java.net.HttpURLConnection; 6 import java.net.URL; 7  8 import org. 9 10 import android.app.Activity;11 import android.graphics.Bitmap;12 import android.graphics.BitmapFactory;13 import android.os.Bundle;14 import android.os.StrictMode;15 import android.widget.ImageView;16 17 /**18  * 19  * @author Administrator 从网上下载图片然后展示在屏幕上20  * 21 */22 23 public class MyWebDemo extends Activity {24   private static final String PATH = "http://a.hiphotos.baidu.com/album/w%3D2048/sign=5c4fe8d4a5c27d1ea5263cc42fedac6e/024f78f0f736afc3f1416515b219ebc4b7451274.jpg";25   private ImageView img = null;26 27   @Override28   protected void onCreate(Bundle savedInstanceState) {29     // TODO Auto-generated method stub30     super.onCreate(savedInstanceState);31     super.setContentView(R.layout.main_http);32     this.img = (ImageView) super.findViewById(R.id.img);33 34     StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()35         .detectDiskReads().detectDiskWrites().detectNetwork()36         .penaltyLog().build());37     StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()38         .detectLeakedSqlLiteObjects().detectLeakedClosableObjects()39         .penaltyLog().penaltyDeath().build());40     try {41       byte data[] = this.getUrlData();42       Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);43       this.img.setImageBitmap(bm);44     } catch (Exception e) {45       e.printStackTrace();46     }47   }48 49   public byte[] getUrlData() throws Exception {50     ByteArrayOutputStream bos = null;51     try {52       //定义URl53       URL url = new URL(PATH);54       //定义内存输入流55       bos = new ByteArrayOutputStream();56       //每次读取1024个57       byte data[] = new byte[1024];58       //打开59       HttpURLConnection conn = (HttpURLConnection) url.openConnection();60       //取得输入流61       InputStream inputStream = conn.getInputStream();62       int len = 0;63       //读取到底部64       while ((len = inputStream.read(data)) != -1) {65         bos.write(data, 0, len);66       }67       //变成字节数组返回68       return bos.toByteArray();69     } catch (Exception e) {70       throw e;71     } finally {72       if (bos != null) {73         //关闭流74         bos.close();75       }76     }77   }78 }


<uses-permission android:name="android.permission.INTERNET" />