Esempio n. 1
0
  @Override
  public CachedImage read(CachedImageKey key) {
    long startRead = System.currentTimeMillis();
    String realPath = getRealPath(key);
    if (realPath == null) {
      return null;
    }

    File file = new File(realPath);
    byte[] fileBytes = null;
    InputStream fis = null;
    try {
      fis = new FileInputStream(file);
      fis = new BufferedInputStream(fis, 8192);
      int offset = 0;
      int byteCount = (int) file.length();
      int readCount = 0;

      fileBytes = new byte[byteCount];
      while ((readCount = fis.read(fileBytes, offset, byteCount)) > 0) {
        offset += readCount;
        byteCount -= readCount;
      }
    } catch (FileNotFoundException e) {
      if (Logger.isDebug()) e.printStackTrace();
    } catch (IOException e) {
      if (Logger.isDebug()) e.printStackTrace();
    } catch (Exception e) {
      if (Logger.isDebug()) e.printStackTrace();
    } finally {
      if (fis != null) {
        try {
          fis.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }

    BitmapFactory.Options options = new BitmapFactory.Options();
    // 先指定原始大小
    options.inSampleSize = 1;
    // 只进行大小判断
    options.inJustDecodeBounds = true;
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
    BitmapFactory.decodeByteArray(fileBytes, 0, fileBytes.length, options);

    long bitmapSize = ImageUtil.calculateBitmapSize(options);
    if (bitmapSize >= BIG_IMG_SIZE_LEVEL) {
      options.inSampleSize = ImageUtil.getScaleSampleSize(options, 120);
      if (Logger.isDebug()) Log.d(TAG, "compress local big bitmap");
    }
    options.inJustDecodeBounds = false;
    Bitmap bitmap = BitmapFactory.decodeByteArray(fileBytes, 0, fileBytes.length, options);

    CachedImage wrap = new CachedImage(bitmap);

    long endRead = System.currentTimeMillis();
    if (Logger.isDebug()) Log.d(TAG, "read local bitmap use time: " + (endRead - startRead) + "ms");
    return wrap;
  }