6.Android 加载图片

package com.wjl.web;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.util.ByteArrayBuffer;

import android.R.string;

public class ImageService {
  public static byte[] getImage(String path) throws Exception
  {
	  URL url=new URL(path);
	  HttpURLConnection connection=(HttpURLConnection)url.openConnection();
	  //必须大写 设置响应头
	  connection.setRequestMethod("GET");
	  //设置延时
	  connection.setConnectTimeout(60000);
	  InputStream instream=connection.getInputStream();
	  //字节数组输出流
	  ByteArrayOutputStream bos=new ByteArrayOutputStream();
	
	  byte[] buffer=new byte[9024];
	  int len=0;
	  while((len=instream.read(buffer))!=-1)
	  {
		  bos.write(buffer,0,len);
	  }
	  //封装
	  byte[] data=bos.toByteArray();
	  return data;
  }
}

package com.wjl.web;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class WebTestActivity extends Activity implements OnClickListener {
	private Button btn;
	
	private ImageView imageview;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btn=(Button)findViewById(R.id.button1);
        imageview=(ImageView)findViewById(R.id.imageView);
        btn.setOnClickListener(this);
    }
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
		if(btn==v)
		{
             String path="http://a.hiphotos.baidu.com/image/w%3D2048/sign=56c7671cbb389b5038ffe752b10de5dd/9d82d158ccbf6c81e01c51eabe3eb13533fa408c.jpg";
		     try {
				byte[] data=ImageService.getImage(path);
				Bitmap bitmap=BitmapFactory.decodeByteArray(data, 0, data.length);
				imageview.setImageBitmap(bitmap);
			} catch (Exception e) {
				// TODO: handle exception
				Log.e("TAG", e.toString());
				Toast.makeText(this, "Error", Toast.LENGTH_LONG).show();
				
			}
		}
		
	}
    

    
    
    
}


 

 

你可能感兴趣的:(6.Android 加载图片)