河东租房,爱的供养陶笛简谱,统计图的种类
android链接服务器获取图片在此提供三种方法,已通过验证,无误。
方法一:
public static bitmap getimage(string path){ try { httpurlconnection conn = (httpurlconnection) new url(path).openconnection(); conn.setconnecttimeout(5000); conn.setrequestmethod("get"); system.out.println("tdw1"); if(conn.getresponsecode() == 200){ inputstream inputstream = conn.getinputstream(); bitmap bitmap = bitmapfactory.decodestream(inputstream); return bitmap; } } catch (exception e) { e.printstacktrace(); } return null; }
在第一种方法中,从conn的输入流中获取数据将其转化为bitmap型数据。
在功能代码中:
image.setimagebitmap(getimage("路径"));
image为imageview型控件。
第二种方法:
public static bitmap getimage1(string path){ httpget get = new httpget(path); httpclient client = new defaulthttpclient(); bitmap pic = null; try { httpresponse response = client.execute(get); httpentity entity = response.getentity(); inputstream is = entity.getcontent(); pic = bitmapfactory.decodestream(is); // 关键是这句代 } catch (exception e) { e.printstacktrace(); } return pic; }
这个方法类似上面那个方法。在功能代码中设置是一样的
第三种方法:
public static uri getimage2(string path,file cachedir){ file localfile = new file(cachedir,md5.getmd5(path)+path.substring(path.lastindexof("."))); if(localfile.exists()){ return uri.fromfile(localfile); }else { httpurlconnection conn; try { conn = (httpurlconnection) new url(path).openconnection(); conn.setconnecttimeout(5000); conn.setrequestmethod("get"); if(conn.getresponsecode() == 200){ system.out.println("tdw"); fileoutputstream outputstream = new fileoutputstream(localfile); inputstream inputstream = conn.getinputstream(); byte[] buffer = new byte[1024]; int length = 0; while((length=inputstream.read(buffer))!=-1){ outputstream.write(buffer, 0, length); } inputstream.close(); outputstream.close(); return uri.fromfile(localfile); } } catch (exception e) { // todo auto-generated catch block e.printstacktrace(); } } return null; }
第三种方法,将从服务器获取的数据存入本地的文件中,如果文件已存在,则不需要从服务器重新获取数据。
在功能代码中:
image.setimageuri(getimage2(path, cache));
上面代码中设置图片为缓存设置,这样如果图片资源更新了,则需要重新命名文件的名字,这样才能够重新加载新图片。
cache = new file(environment.getexternalstoragedirectory(),"cache"); if(!cache.exists()){ cache.mkdirs(); }
这里是设置 缓存图片的路径。
以上为三种方法。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
Android studio开发小型对话机器人app(实例代码)
Android通过Java sdk的方式接入OpenCv的方法
Android 通过cmake的方式接入opencv的方法步骤
Android Studio finish()方法的使用与解决app点击“返回”(直接退出)
Android 进度条 ProgressBar的实现代码(隐藏、出现、加载进度)
网友评论