android programming implements the image library encapsulation method

  • 2020-10-31 21:59:17
  • OfStack

This article illustrates the package method of android programming image library. To share for your reference, the details are as follows:

Everybody when doing the android applications often have to get photo from Internet by URL to obtain but if the local image data from the local to get the data not more speed up 1 this problem encountered in the work so adopted 1 URL and local picture 1 mapping relationship from the first access to the region if local didn't obtain the method from the network considering the multi-thread problem welcome to 1 case to discuss!


public class PictureLibrary {
 /*
  *  The operation of the photo gallery 
  */
 File file;
 URL url;
 HttpURLConnection conn;
 InputStream is;
 FileOutputStream fos;
 private Lock lock = new ReentrantLock();
 private Condition downFile = lock.newCondition();
 //  through URL Download the data to the local operation 
 private String toLocalFile(String strURL) {
  String fileName = Utils.getFileName(strURL);
  String path = Environment.getExternalStorageDirectory() + "/"
    + EcologicalTourism.FILE_PATH + "/images/" + fileName;
  return path;
 }
 //  through URL Download the data to a local temporary file 
 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;
 }
 /*
  *  Save the image to local and return it to local url (This function is blocked) 
  * main
  * @ Parameters: strURL , whose parameters are pictures URL. Return value: The image is local SD Where the card is temporarily stored 
  *  The function is responsible for retrieving images from the Internet, storing them in local storage, and returning the file path to the local storage for direct use by the caller. If the file is already local, return it 
  *  If the file is not local, it is downloaded directly from the server and the function blocks. 
  */
 public String getReadSD(String strURL) {
  Log.i("test", " The address to get the network is: " + strURL);
  String strLocalFile = toLocalFile(strURL); //k : Put the server URL Convert to local URL
  String strLocalFileTemp = toLocalFileTemp(strURL); //k : Put the server URL Convert to local temporary URL
  while (true) {
   File file = new File(strLocalFile);
   Log.i("test", " The local file is: " + strLocalFile);
   File tfile = new File(strLocalFileTemp);
   Log.i("test", " The temporary file is: " + strLocalFileTemp);
   // 1 locked 
   lock.lock();
   if (file.exists()) {
    // 2if  Local file existence 
    //  unlock 
    //  Return local path 
    lock.unlock();
    Log.i("test", " Return local path: " + file);
    return strLocalFile;
   } else if (tfile.exists()) {
    // if  The corresponding temporary file exists 
    //  unlock 
    lock.unlock();
    try {
     //  sleep 
     downFile.await();
    } catch (Exception e) {
      e.printStackTrace();
     Log.i("test", "e  Something is wrong 1" + e);
    }
   } else {
    try {
     //  Create the corresponding staging file 
     tfile.createNewFile();
    } catch (IOException e) {
     Log.i("test", "e  Something is wrong 2" + e);
    }
    //  unlock 
    lock.unlock();
    //  Download the file contents to a temporary file 
    downURL2(strURL, strLocalFile);
    //  locked 
    lock.lock();
    //  Change the temporary file name to the local file name 
    tfile.renameTo(file);
    //  unlock 
    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();
     //  return 1 a URI object 
   }
  } 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();
  }
 }
 /*
  *  Blocking download url To the file  toFile In the 
  */
 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();//  The file size 
   httpUrl.disconnect();//  Close the connection 
   int threadSize = 6;//  The default Settings 6 A thread 
   threadSize = fileSize % threadSize == 0 ? threadSize
     : threadSize + 1;
   int currentSize = fileSize / threadSize; //  Download size per thread 
   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);//  The specified  file  File size 
   for (int i = 0; i < threadSize; i++) {
    int startposition = i * currentSize;//  Where each thread begins writing to the file 
    RandomAccessFile threadFile = new RandomAccessFile(file, "rw");
    Log.i("syso", "toFile The content is as follows: " + toFile);
    threadFile.seek(startposition);
    new DownLoadThread(i, currentSize, threadFile, startposition,
      url).start();
   }
  } catch (Exception e) {
   e.printStackTrace();
   Log.i("syso", "download Download failed " + e);
  }
  return true;
 }
 /**
  *  Implement thread download 
  * 
  */
 private static class DownLoadThread extends Thread {
  @SuppressWarnings("unused")
  private int threadId;//  The thread number 
  private int currentSize;//  The size of each thread 
  private RandomAccessFile threadFile; //  Each thread   To write a file class 
  private int startposition;//  Where each thread begins writing to the file 
  private URL url; // The network address 
  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
      + "-");//  Specifies the location of the server 
    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();
   }
  }
 }
 /**
 *  Gets the image from this cache 
 */
 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;
 }

I hope this article has been helpful in Android programming.


Related articles: