安卓Imageview控件如何获取网络图片

来源:互联网 发布:手机淘宝怎样删除差评 编辑:程序博客网 时间:2024/05/16 09:04

        关于安卓如何获取网络图片的问题,网上有一些代码,但是这些代码大多不能用,出现各种问题;现在把我写的代码贡献出来,和大家一起交流。本代码实现的是点击按钮,将网络图片加载到安卓的Imageview控件上,本人亲试通过。

        首先是打开网络权限:在AndroidManifest.xml文件中写入 <uses-permission android:name="android.permission.INTERNET"/>,然后就是所用的代码:

xml文件:

       <ImageView
         android:id="@+id/imageview"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         />
       <Button
         android:id="@+id/button"
         android:layout_height="wrap_content"
         android:layout_width="fill_parent"
         android:text="获取网络图片"
         />

activity类:

package com.example.imageviewtest;
//获取网络图片的方法
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {
 private ImageView getImageview;
 private Button getButton;
 private final String IMAGE_URL="http://img.hen2.com/201509/source_img/150_G_1442562155435.jpg";//这里是存放网络图片的路径


 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
   getButton = (Button) findViewById(R.id.button);
   getImageview = (ImageView) findViewById(R.id.imageview);
   getButton.setOnClickListener(new View.OnClickListener() { 
   @Override
   public void onClick(View v) {
        new Thread(runa).start();
   }
  });
 }
 
// 获取网络图片
 public void setView(String path) {
    String picturepath = path;
    byte[] data = null;
    try {
     data = getImage(picturepath);
     Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
     Looper.prepare();
     Message msg = new Message();
     msg.what = 0;
     msg.obj = bitmap;
     handler.sendMessage(msg);
    } catch (Exception e) {
     Toast.makeText(getApplicationContext(), "获取图片错误", 1).show();
    }
   }
 
//定义一个handler给imageview绑定图片
   private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
     if (msg.what == 0) {
      getImageview.setImageBitmap((Bitmap) msg.obj);
     }
    }
   };
 
//定义一个Runnable,调用获取网络图片的方法
   private Runnable runa = new Runnable() {
    @Override
    public void run() {
     setView(IMAGE_URL);
    }
   };
  
   // 获取网络图片的数据
   public static byte[] getImage(String picturepath) throws Exception {
               URL url = new URL(picturepath);
               HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 基于http协议的连接对象
               conn.setConnectTimeout(10000);// 10秒(源码有问题,把10(10毫秒)改为了10000(10秒)现在正确了)
               conn.setRequestMethod("GET");// 大写
              if (conn.getResponseCode() == 200) {
                InputStream ins = conn.getInputStream();
                 return read(ins);
                }
               return null;
          }
   

 //流工具
     public static byte[] read(InputStream ins) throws Exception {
           ByteArrayOutputStream outstream = new ByteArrayOutputStream();
           byte[] buffer = new byte[1024];
           int length = 0;
           while ((length = ins.read(buffer)) > -1) {
             outstream.write(buffer, 0, length);
           }
           outstream.close();
          return outstream.toByteArray();
       }
   
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }

}

0 0
原创粉丝点击