android从网络获取图片

android从网络上获取图片的方法有很多,这里通过HttpURLConnecion进行网络连接,并将得到的InputStream解码成Bitmap显示在ImageView上,下面贴上简单的demo:

1、可以通过安装Tomcat服务器,通过MyEclipse或者J2ee建立自己的web工程,在WebRoot路径下面放置一张图片这里为jon.png,web工程名这里为FirstProject,启动工程,在浏览器中输入:http://192.168.13.100:8080/FirstProject/jon.png,查看图片显示是否正确,不正确请检查端口或者路径有没有输入错误;

2、建立android工程

1)、GetImageActivity.java

package com.example.test;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;


/**
 * 
 *  Class Name: GetImageActivity.java
 *  Function:
 *  
 *     Modifications:   
 *  
 *  @author jon  DateTime 2015-12-1 上午10:57:08    
 *  @version 1.0
 */
public class GetImageActivity extends Activity implements OnClickListener {
    
    private EditText mImagePath;
    private Button mImageBtn;
    private Button mUserBtn;
    private ImageView mImageView;
    
    private static final int BITMAP_MESSGAE=0X1123;
    
    private Handler mHandler=new Handler()
    {
        public void handleMessage(android.os.Message msg) {
        switch (msg.what) {
        case 0x1123:
            
            Bitmap mBitmap=(Bitmap) msg.obj;
            if (null!=mBitmap) {
                mImageView.setImageBitmap(mBitmap);
            }
            break;

        default:
            break;
        }
        
        
    };
        
    };
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.image_show);
        initViews();
        initListeners();
    }

    private void initListeners() {
        mImageBtn.setOnClickListener(this);
        mUserBtn.setOnClickListener(this);
    }

    private void initViews() {
        
        mImagePath=(EditText) findViewById(R.id.img_path);
        mImageBtn=(Button) findViewById(R.id.img_button);
        mUserBtn=(Button) findViewById(R.id.user_button);
        mImageView=(ImageView) findViewById(R.id.img_show);
        
    }

    @Override
    public void onClick(View v) {
        
        switch (v.getId()) {
        case R.id.img_button:
            showImage();
            break;
            
        case R.id.user_button:
            //showUser();
            break;

        default:
            break;
        }//switch
        
    }


    private void showImage() {
        
        final String mPath=mImagePath.getText().toString();
        
        new Thread(new Runnable() {
            
            @Override
            public void run() {
                Bitmap mBitmap=ImageService.getBitmapFromUrl(mPath);
                Message msg=new Message();
                msg.obj=mBitmap;
                msg.what=BITMAP_MESSGAE;
                mHandler.sendMessage(msg);
                
            }
        }).start();
        
        
    }
    
}

2)、ImageService.java 图片服务类

package com.example.test;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.v4.util.LruCache;
import android.widget.ImageView;
/**
 * 
 *  Class Name: ImageService.java
 *  Function:
 *  图片服务类,将下载和更新的操作在此类实现
 *     Modifications:   
 *  
 *  @author jon  DateTime 2015-12-3 下午3:25:03    
 *  @version 1.0
 */
public class ImageService {
    
    private ImageView mImageView;
    private String mImgUrl;
    private LruCache<String, Bitmap> mMemoryCache;

    
    public ImageService() 
    {
        
       int mMaxMemory=(int) Runtime.getRuntime().maxMemory();
       int mCacheSize=mMaxMemory/8;
       mMemoryCache=new LruCache<String, Bitmap>(mCacheSize)
               {
                 protected int sizeOf(String key, Bitmap value) 
                 {
                      return value.getRowBytes()*value.getHeight();
                 }
               };
    }
    
    
    /**
     * 
     *  Function:
     *  從緩存中取出圖片
     *  @author jon  DateTime 2015-12-4 下午2:05:36
     *  @param key
     *  @return
     */
    public Bitmap getBitmapFromCache(String key) {
        return mMemoryCache.get(key);
    }
    
    /**
     *  將圖片添加到緩存
     *  Function:
     * 
     *  @author jon  DateTime 2015-12-4 下午2:05:05
     *  @param key
     *  @param mBitmap
     */
    public void addBitmapToCache(String key,Bitmap mBitmap) {
        if (mMemoryCache.get(key)==null&&mBitmap!=null) {
            mMemoryCache.put(key, mBitmap);
        }
    }
    
    private Handler mHandler=new Handler(){
        
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case Constants.MESSAGE_URL:
                Bitmap mBitmap=(Bitmap) msg.obj;
                if (mImageView.getTag().equals(mImgUrl)) {
                    mImageView.setImageBitmap(mBitmap);
                }
                
                break;

            default:
                break;
            }
            
        };
    };
    
    /**
     * 
     *  Function:
     *  通过线程获取网络中的图片,并通过handler将图片信息发给主线程进行UI更新
     *  @author jon  DateTime 2015-12-3 下午3:23:33
     *  @param mImageView
     *  @param url
     */
    public void setImageBitmap(ImageView mImageView,final String url) {
        
           this.mImageView=mImageView;
           this.mImgUrl=url;
            
            new Thread(new Runnable() {
                
                @Override
                public void run() {
                    Bitmap mBitmap=null;
                    if (mMemoryCache.get(url)!=null) {
                        mBitmap=getBitmapFromCache(url);
                    }else
                    {
                        mBitmap=getBitmapFromUrl(url);
                        addBitmapToCache(url, mBitmap);
                    }
                    Message msg=new Message();
                    msg.what=Constants.MESSAGE_URL;
                    msg.obj=mBitmap;
                    mHandler.sendMessage(msg);
                }
            }).start();
        
    }
    
    /**
     * 
     *  Function:
     *  通过url从网络获取图片
     *  @author jon  DateTime 2015-12-3 下午3:22:43
     *  @param path
     *  @return
     */
    public static Bitmap getBitmapFromUrl(String path)
    {
        URL mUrl=null;
        HttpURLConnection mConn=null;
        InputStream mIs=null;
        Bitmap mBitmap=null;
        
        try {
            mUrl=new URL(path);
            mConn=(HttpURLConnection) mUrl.openConnection();
            mConn.setConnectTimeout(5000);
            mConn.setRequestMethod("GET");
            
            if (mConn.getResponseCode()==200) {
                mIs=mConn.getInputStream();
                mBitmap=BitmapFactory.decodeStream(mIs);
            }
            return mBitmap;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }
        finally
        {
            if (null!=mConn) {
                mConn.disconnect();
            }
            
            if (null!=mIs) {
                try {
                    mIs.close();
                } catch (IOException e) {
                }
            }
        }
        
        return null;
    }

}

3)、layout显示:image_show.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/text_path"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:layout_marginBottom="@dimen/margin_pading"
        android:layout_marginTop="@dimen/margin_pading"
        android:layout_marginLeft="@dimen/margin_pading"
        android:text="@string/image_path" />

    <EditText
        android:id="@+id/img_path"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/image_string"
        android:layout_marginBottom="@dimen/margin_pading"
        android:ems="10" >

    </EditText>
    
    <LinearLayout 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >
        
         <Button
        android:id="@+id/img_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/margin_pading"
        android:text="@string/image_obtain" />
         
           <Button
        android:id="@+id/user_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/margin_pading"
        android:text="@string/user_obtain" />
        
        
    </LinearLayout>

   
    <View 
        android:layout_width="match_parent"
        android:layout_height="1dp"
         android:layout_marginBottom="@dimen/margin_pading"
        android:background="#999999"
        />

    <ImageView
        android:id="@+id/img_show"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center_horizontal"
        android:scaleType="fitXY"
        android:src="@drawable/ic_launcher" />

</LinearLayout>

4)、manifest中记得加入网络权限:

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

经过上面四步,简单的从网络获取图片的代码就可以正常显示了.

 

posted @ 2016-04-12 10:33  伟雪无痕  阅读(263)  评论(0)    收藏  举报