本文執行個體講述了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程式設計有所協助。