android中获取网络图片
本主要介绍在android如何获取网络图片的方法,其源代码如下:
- package com.demo.lc;
- import java.io.ByteArrayOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.net.HttpURLConnection;
- import java.net.URL;
- 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.EditText;
- import android.widget.ImageView;
- import android.widget.Toast;
- public class ImageViewActivity extends Activity implements OnClickListener{
- /**网络路径输入框*/
- private EditText mEt_url = null;
- /**读取网络图片*/
- private Button mBtn_read = null;
- /**显示网络图片*/
- private ImageView mIv_show = null;
- /**路径Url*/
- private URL mUrl = null;
- /**http连接*/
- private HttpURLConnection mConn = null;
- /**存储图片的二进制数组*/
- private byte[] mPic = null;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- super.setContentView(R.layout.main);
- //初始化组件
- initWidget();
- this.mBtn_read.setOnClickListener(this);
- }
- private void initWidget() {
- //实例化EditText
- mEt_url = (EditText) super.findViewById(R.id.et_urlpath);
- //实例化Button
- mBtn_read = (Button) super.findViewById(R.id.btn_display);
- //实例化ImageView
- mIv_show = (ImageView) super.findViewById(R.id.iv_show);
- }
- @Override
- public void onClick(View v) {
- InputStream mIs = null;
- try {
- //实例化mUrl
- mUrl = new URL(mEt_url.getText().toString());
- //建立Http网络连接
- mConn = (HttpURLConnection) mUrl.openConnection();
- //设置请求方式为GET
- mConn.setRequestMethod("GET");
- //设置超时时间为5秒
- mConn.setConnectTimeout(5000);
- //获取图片的输入
- mIs = mUrl.openStream();
- //获取图片的二进制数组
- mPic = getByteArray(mIs);
- System.out.println(mPic.length);
- mIs.close();
- } catch (Exception e) {
- //当连接超时的时候会弹出Toast
- Toast.makeText(this,R.string.error, 100).show();
- e.printStackTrace();
- }
- mIv_show.setImageBitmap(BitmapFactory.decodeByteArray(mPic, 0, mPic.length));
- }
- private byte[] getByteArray(InputStream is) {
- //用于向内存中写字节的字节数组输出流
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- //字节数组缓冲区
- byte[] temp = new byte[1024];
- //读取字节的长度
- int len = 0;
- try {
- //以二进制的形式读入
- while((len=is.read(temp))!=-1){
- bos.write(temp, 0, len);
- }
- is.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- //转化为字节数组
- return bos.toByteArray();
- }
- }
效果如下:
转载于:https://blog.51cto.com/splend/967186