private Bitmap getBitmapFromUrl(String imgUrl, int minSide, int maxPixels) { URL url; Bitmap bitmap = null; try { url = new URL(imgUrl); InputStream is = url.openConnection().getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); bitmap = BitmapLoader.getThumbnail(bis, minSide, maxPixels); bis.close(); is.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return bitmap; }
public void run() { if (desc == null) { return; } Bitmap bitmap = null; // 如果用户自定义了下载图片的方式,则调用用户的 if (hasLoader(desc)) { bitmap = invokeLoader(desc); if (null != bitmap) { desc.bitmap = bitmap; if (desc.imageLoader.isCacherToFile()) { File file = desc.imageLoader.cacheFile(); if (null != file && saveToPath(file, bitmap)) {} } notifyLoadResult(desc, true, desc.imageLoader.isCacheToMemery()); } else { notifyLoadResult(desc, false, false); } return; } if (desc.filePath != null) { try { bitmap = BitmapLoader.getThumbnail(desc.filePath, desc.minSide, desc.maxPixels); } catch (Exception e) { e.printStackTrace(); } if (bitmap != null) { desc.bitmap = bitmap; notifyLoadResult(desc, true, true); } else { notifyLoadResult(desc, false, false); } } else { // 先从文件中读. if (null != desc.key) { String path = desc.path == null ? cachePath : desc.path; File cacheFile = new File(path, desc.key); if (cacheFile.exists()) { // BitmapFactory.Options opt = new BitmapFactory.Options(); // opt.inPreferredConfig = Bitmap.Config.RGB_565; // opt.inPurgeable =true; // opt.inInputShareable = true; bitmap = BitmapLoader.getThumbnail(cacheFile.getPath(), desc.minSide, desc.maxPixels); } if (null != bitmap) { desc.bitmap = bitmap; notifyLoadResult(desc, true, true); return; } } // 如果文件读取失败则从网络下载 if (bitmap == null && null != desc.url) { try { bitmap = getBitmapFromUrl(desc.url, desc.minSide, desc.maxPixels); if (null == bitmap) throw new Exception("bitmap is null ,http request failed"); // 存入本地再缓存在内存 String path = desc.path == null ? cachePath : desc.path; String key = desc.key == null ? desc.url.substring(desc.url.lastIndexOf("/") + 1) : desc.key; File dir = new File(path); dir.mkdirs(); // 清空缓存的策越,目前是大于100M就将缓存全部清空 if (dir.length() > MAX_CACHE_FILE_SIZE) clearFileCache(path); File file = new File(path, key); if (saveToPath(file, bitmap)) { desc.bitmap = bitmap; notifyLoadResult(desc, true, true); } else { desc.description = "保存图片失败(可能原因图片无效)"; notifyLoadResult(desc, false, false); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); desc.description = e.getMessage(); notifyLoadResult(desc, false, false); } } } }