1 package com.example.test.widget; 2 3 import java.io.ByteArrayOutputStream; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.net.HttpURLConnection; 7 import java.net.MalformedURLException; 8 import java.net.URL; 9 import java.net.URLConnection; 10 11 import android.content.Context; 12 import android.graphics.Bitmap; 13 import android.graphics.BitmapFactory; 14 import android.os.Handler; 15 import android.os.Message; 16 import android.util.AttributeSet; 17 import android.widget.ImageView; 18 19 /** 20 * 自定义imageview,可显示网络图片 21 * 22 * @author huaf22@gmail.com 23 * @date 2013-10-5 下午8:21:24 24 */ 25 public class NetImageView extends ImageView { 26 public NetImageView(Context context) { 27 super(context); 28 // TODO Auto-generated constructor stub 29 } 30 31 public NetImageView(Context context, AttributeSet attrs) { 32 super(context, attrs); 33 } 34 35 Handler handler = new Handler() { 36 37 @Override 38 public void handleMessage(Message msg) { 39 // TODO Auto-generated method stub 40 byte[] data = (byte[]) msg.obj; 41 if (data != null) { 42 Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, 43 data.length); 44 setImageBitmap(bitmap);// 显示图片 45 } 46 } 47 48 }; 49 50 public void setNetImage(final String path) { 51 new Thread(new Runnable() { 52 public void run() { 53 handler.sendMessage(handler.obtainMessage(21, httpServer(path))); 54 } 55 }).start(); 56 } 57 58 private byte[] httpServer(String imagepath) { 59 HttpURLConnection conn = null; 60 InputStream is = null; 61 ByteArrayOutputStream os = new ByteArrayOutputStream(); 62 try { 63 conn = (HttpURLConnection) new URL(imagepath).openConnection(); 64 conn.setConnectTimeout(5000); 65 conn.setRequestMethod("GET"); 66 if (conn.getResponseCode() == 200) { 67 is = ((URLConnection) conn).getInputStream(); 68 byte[] buffer = new byte[1024]; 69 int len = 0; 70 while ((len = is.read(buffer)) != -1) { 71 os.write(buffer, 0, len); 72 } 73 return os.toByteArray(); 74 } 75 } catch (MalformedURLException e) { 76 // TODO Auto-generated catch block 77 e.printStackTrace(); 78 } catch (IOException e) { 79 // TODO Auto-generated catch block 80 e.printStackTrace(); 81 } finally { 82 try { 83 is.close(); 84 85 } catch (IOException e) { 86 // TODO Auto-generated catch block 87 e.printStackTrace(); 88 } 89 } 90 return null; 91 } 92 }
使用方法:
1 <com.example.test.widget.NetImageView 2 android:id="@+id/imageView1" 3 android:layout_width="wrap_content" 4 android:layout_height="wrap_content" 5 android:layout_alignLeft="@+id/button1" 6 android:layout_below="@+id/button1" 7 android:layout_marginTop="80dp" 8 android:src="@drawable/ic_launcher" />
1 private NetImageView imageview = null; 2 3 private String imagepath="http://192.168.1.102:8080/APP/usrIcon/002.jpg"; 4 5 imageview = (NetImageView) findViewById(R.id.imageView1); 6 7 imageview.setNetImage(imagePath);
缺点:
1.不能加载多个大图片,会产生内存溢出
2.没有线程数量控制,加载N多图片时,会产生N多线程
我会在以后的版本里继续改进。。。