当前位置: 移动技术网 > 移动技术>移动开发>Android > android编程实现图片库的封装方法

android编程实现图片库的封装方法

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

本文实例讲述了android编程实现图片库的封装方法。分享给大家供大家参考,具体如下:

大家在做安卓应用的时候 经常要从网络中获取图片 都是通过url去获取 可是如果本地有图片数据 从本地获取数据不更加快一些 自己在工作中遇到这个问题 所以采用了一个url和本地图片的一个映射关系 先从本地区获取 假如本地没有再从网络中获取 本方法考虑到多线程问题 欢迎大家一起共同探讨!

public class picturelibrary {
 /*
  * 图片库的操作
  */
 file file;
 url url;
 httpurlconnection conn;
 inputstream is;
 fileoutputstream fos;
 private lock lock = new reentrantlock();
 private condition downfile = lock.newcondition();
 // 通过url将数据下载到本地操作
 private string tolocalfile(string strurl) {
  string filename = utils.getfilename(strurl);
  string path = environment.getexternalstoragedirectory() + "/"
    + ecologicaltourism.file_path + "/images/" + filename;
  return path;
 }
 // 通过url将数据下载到本地临时文件中
 private string tolocalfiletemp(string strurl) {
  string s = utils.getfilename(strurl);
  string filename = s+"temp";
  string path_url = environment.getexternalstoragedirectory() + "/"
    + ecologicaltourism.file_path + "/tempimages/" + filename;
  return path_url;
 }
 /*
  * 保存图片到本地,并返回本地url(此函数是阻塞的)
  * main
  * @参数:strurl,参数为图片的url.返回值:该图片在本地sd卡暂存的位置
  * 函数的工作是负责将图片从互联网上取得,存在本地存储中,并返回本地存储的文件路径,供调用者直接使用。如果文件已经存在本地,直接返回
  * 如果文件未在本地,则直接从服务器下载,函数阻塞。
  */
 public string getreadsd(string strurl) {
  log.i("test", "拿到网络的地址是:" + strurl);
  string strlocalfile = tolocalfile(strurl); //k:把服务器url转换为本地url
  string strlocalfiletemp = tolocalfiletemp(strurl); //k:把服务器url转换为本地临时url
  while (true) {
   file file = new file(strlocalfile);
   log.i("test", "本地文件是:" + strlocalfile);
   file tfile = new file(strlocalfiletemp);
   log.i("test", "临时文件是:" + strlocalfiletemp);
   // 1上锁
   lock.lock();
   if (file.exists()) {
    // 2if 本地文件存在
    // 解锁
    // 返回本地路径
    lock.unlock();
    log.i("test", "返回本地路径:" + file);
    return strlocalfile;
   } else if (tfile.exists()) {
    // if 对应的暂存文件存在
    // 解锁
    lock.unlock();
    try {
     // 睡眠
     downfile.await();
    } catch (exception e) {
      e.printstacktrace();
     log.i("test", "e 出现了异常1" + e);
    }
   } else {
    try {
     // 创建对应的暂存文件
     tfile.createnewfile();
    } catch (ioexception e) {
     log.i("test", "e 出现了异常2" + e);
    }
    // 解锁
    lock.unlock();
    // 下载文件内容到暂存文件中
    downurl2(strurl, strlocalfile);
    // 上锁
    lock.lock();
    // 修改暂存文件名字为本地文件名
    tfile.renameto(file);
    // 解锁
    lock.unlock();
   }
  }
 }
 private void downurl2(string strurl, string strlocalfiletemp) {
  // todo auto-generated method stub
  url url;
  try {
   url = new url(strurl);
   httpurlconnection conn = (httpurlconnection) url.openconnection();
   conn.setconnecttimeout(5000);
   conn.setrequestmethod("get");
   conn.setdoinput(true);
   if (conn.getresponsecode() == 200) {
     inputstream is = conn.getinputstream();
     fileoutputstream fos = new fileoutputstream(strlocalfiletemp);
     byte[] buffer = new byte[1024];
     int len = 0;
     while ((len = is.read(buffer)) != -1) {
       fos.write(buffer, 0, len);
     }
     is.close();
     fos.close();
     // 返回一个uri对象
   }
  } catch (malformedurlexception e) {
   // todo auto-generated catch block
   e.printstacktrace();
  } catch (protocolexception e) {
   // todo auto-generated catch block
   e.printstacktrace();
  } catch (ioexception e) {
   // todo auto-generated catch block
   e.printstacktrace();
  }
 }
 /*
  * 阻塞式下载url到文件 tofile中
  */
 private boolean downurl(string strurl, string tofile) {
  url url;
  try {
   url = new url(strurl);
   httpurlconnection httpurl = (httpurlconnection) url
     .openconnection();
   httpurl.setrequestmethod("get");
   int filesize = httpurl.getcontentlength();// 文件大小
   httpurl.disconnect();// 关闭连接
   int threadsize = 6;// 默认设置6个线程
   threadsize = filesize % threadsize == 0 ? threadsize
     : threadsize + 1;
   int currentsize = filesize / threadsize; // 每条线程下载大小
   string dowloadir = environment.getexternalstoragedirectory() + "/"
     + ecologicaltourism.file_path + "/images/";
   file dir = new file(dowloadir);
   if (!dir.exists()) {
    dir.mkdirs();
   }
   file file = new file(dir, tofile);
   randomaccessfile randomfile = new randomaccessfile(file, "rw");
   randomfile.setlength(filesize);// 指定 file 文件的大小
   for (int i = 0; i < threadsize; i++) {
    int startposition = i * currentsize;// 每条线程开始写入文件的位置
    randomaccessfile threadfile = new randomaccessfile(file, "rw");
    log.i("syso", "tofile的内容是:" + tofile);
    threadfile.seek(startposition);
    new downloadthread(i, currentsize, threadfile, startposition,
      url).start();
   }
  } catch (exception e) {
   e.printstacktrace();
   log.i("syso", "download下载失败" + e);
  }
  return true;
 }
 /**
  * 实现线程下载
  * 
  */
 private static class downloadthread extends thread {
  @suppresswarnings("unused")
  private int threadid;// 线程编号
  private int currentsize;// 每条线程的大小
  private randomaccessfile threadfile; // 每条线程 要写入文件类
  private int startposition;// 每条线程开始写入文件的位置
  private url url; //网络地址
  public downloadthread(int threadid, int currentsize,
    randomaccessfile threadfile, int startposition, url url) {
   this.threadid = threadid;
   this.currentsize = currentsize;
   this.threadfile = threadfile;
   this.startposition = startposition;
   this.url = url;
  }
  public void run() {
   try {
    httpurlconnection httpurl = (httpurlconnection) url
      .openconnection();
    httpurl.setrequestmethod("get");
    httpurl.setrequestproperty("range", "bytes=" + startposition
      + "-");// 指定服务器的位置
    inputstream is = httpurl.getinputstream();
    byte[] data = new byte[1024];
    int len = -1;
    int threadfilesize = 0;
    while ((threadfilesize < currentsize)
      && ((len = is.read(data)) != -1)) {
     threadfile.write(data, 0, len);
     threadfilesize += len;
    }
    httpurl.disconnect();
    is.close();
   } catch (exception e) {
    e.printstacktrace();
   }
  }
 }
 /**
 * 从本缓存中获取图片
 */
 public bitmap getbitmapfromcache(string imageurl) {
 // string bitmapname = imageurl.substring(imageurl.lastindexof("/") + 1); 
  string bitmapname = utils.getfilename(imageurl);
  file cachedir = new file(environment.getexternalstoragedirectory() + "/"
    + ecologicaltourism.file_path + "/images/");
  file[] cachefiles = cachedir.listfiles();
  int i = 0;
  if(null!=cachefiles){
   for(; i<cachefiles.length;i++){
    if(bitmapname.equals(cachefiles[i].getname())){
     break;
    }
   }
   if(i < cachefiles.length)
   {
    return bitmapfactory.decodefile(environment.getexternalstoragedirectory() + "/"
      + ecologicaltourism.file_path + "/images/" + bitmapname);
   }
  }
  return null;
 }

希望本文所述对大家android程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网