当前位置: 移动技术网 > IT编程>移动开发>Android > Android 通过网络图片路径查看图片实例详解

Android 通过网络图片路径查看图片实例详解

2019年07月24日  | 移动技术网IT编程  | 我要评论

性爱知识,阳谷招聘信息,非诚勿扰孟雪牵手

android 通过网络图片路径查看图片实例详解

1.在项目清单中添加网络访问权限

<!--访问网络的权限--> 
<uses-permission android:name="android.permission.internet"/> 

2.获取网络图片数据

/** 
   * 获取网络图片的数据 
   * @param path 网络图片路径 
   * @return 
   * @throws exception 
   */ 
  public static byte[] getimage(string path) throws exception { 
    url url=new url(path); 
    httpurlconnection conn=(httpurlconnection)url.openconnection();//得到基于http协议的连接对象 
    conn.setconnecttimeout(5000);//设置超时时间 
    conn.setrequestmethod("get");//请求方式 
    if(conn.getresponsecode()==200){//判断是否请求成功 
      inputstream inputstream=conn.getinputstream(); 
      return read(inputstream); 
    } 
    return null; 
  } 
  /** 
   * 读取流中的数据 
   */ 
  public static byte[] read(inputstream inputstream) throws ioexception { 
    bytearrayoutputstream outputstream=new bytearrayoutputstream(); 
    byte[] b=new byte[1024]; 
    int len=0; 
    while((len=inputstream.read(b))!=-1){ 
      outputstream.write(b); 
    } 
    inputstream.close(); 
    return outputstream.tobytearray(); 
  } 

3.处理查看图片的控制

public class netimageactivity extends activity { 
  private edittext pathtext; 
  private imageview imageview; 
  @override 
  public void oncreate(bundle savedinstancestate) { 
    super.oncreate(savedinstancestate); 
    setcontentview(r.layout.main); 
     
    pathtext=(edittext)this.findviewbyid(r.id.imagepath);//图片路径 
    imageview=(imageview)this.findviewbyid(r.id.imageview);//显示图片控件 
    button button=(button)this.findviewbyid(r.id.button);//查看图片按钮 
    button.setonclicklistener(new buttonclicklistener());//注册查看图片按钮事件 
  } 
  /** 
   * 处理查看图片按钮事件 
   */ 
  private final class buttonclicklistener implements view.onclicklistener{ 
    @override 
    public void onclick(view v) { 
      //取得图片路径 
      string path=pathtext.gettext().tostring(); 
      try { 
        //获取图片数据 
        byte[] data=imageservice.getimage(path); 
        //使用数组的所有数据构建位图对象 
        bitmap bitmap=bitmapfactory.decodebytearray(data, 0, data.length); 
        imageview.setimagebitmap(bitmap);//显示图片 
      } catch (exception e) { 
        e.printstacktrace(); 
        toast.maketext(getapplicationcontext(), r.string.error, 1).show(); 
      } 
    } 
  } 
} 


感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网