从网络上获取图片

效果图如下所示:点击按钮,图片显示


代码如下:

package kongjian;

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

import javax.net.ssl.HttpsURLConnection;

import org.apache.http.protocol.HttpContext;

import com.example.kongjian.R;

import android.R.integer;
import android.app.Activity;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

/**
 * 从网络上获取图片
 * 
 * @author DongYan
 * 
 */
public class ImageViewInternet extends Activity {
	private ImageView image;
	private Button btn_image;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.imageviewinternet);
		image = (ImageView) findViewById(R.id.image);
		btn_image = (Button) findViewById(R.id.btn_image);

		btn_image.setOnClickListener(new ClickListener());
	}

	class ClickListener implements OnClickListener {
		/**
		 * 点击按钮从网络获取图片
		 */
		@Override
		public void onClick(View v) {
			byte [] imageget= ImageGet();
			image.setImageBitmap(BitmapFactory.decodeByteArray(imageget, 0, imageget.length));
		}

	}
	/**
	 * 从网络获取图片的方法
	 * @return
	 */
	public byte[] ImageGet() {
		ByteArrayOutputStream byteArroutSream = new ByteArrayOutputStream();
		
		try {
			URL url = new URL(
					"http://pic.baike.soso.com/p/20090715/20090715173716-552026492.jpg");//图片在网络上的地址
			HttpURLConnection connection =(HttpURLConnection) url.openConnection();
			connection.setConnectTimeout(3000);// 设置链接超时
			// 获取服务器响应
			connection.setDoInput(true);
			// 请求方式
			connection.setRequestMethod("GET");
			// 得到响应码
			int code = connection.getResponseCode();
			if (code == 200) {// 响应成功
				// 拿到图片信息
				InputStream stream = connection.getInputStream();
				// 将信息已字节的形式存储
				byte[] data = new byte[6078];
				int len;
				while ((len = stream.read(data)) != -1) { // 如果没有读完
					// 将写到数组中
					byteArroutSream.write(data, 0, len);

				}

			}
		

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return  byteArroutSream.toByteArray();

	
	}
	
}



还要注意的一点是要在AndroidManifest.xml 中添加权限

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





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值