Ejemplo n.º 1
1
 protected Bitmap createScaledBitmapFromStream(
     InputStream s, int minimumDesiredBitmapWidth, int minimumDesiredBitmapHeight) {
   BufferedInputStream is = new BufferedInputStream(s, 32768);
   try {
     Options decodeBitmapOptions = new Options();
     if (minimumDesiredBitmapWidth > 0 && minimumDesiredBitmapHeight > 0) {
       Options decodeBoundsOptions = new Options();
       decodeBoundsOptions.inJustDecodeBounds = true;
       is.mark(32768);
       BitmapFactory.decodeStream(is, null, decodeBoundsOptions);
       is.reset();
       decodeBitmapOptions.inSampleSize =
           Math.max(
               1,
               Math.min(
                   decodeBoundsOptions.outWidth / minimumDesiredBitmapWidth,
                   decodeBoundsOptions.outHeight / minimumDesiredBitmapHeight));
     }
     Bitmap decodeStream = BitmapFactory.decodeStream(is, null, decodeBitmapOptions);
     try {
       is.close();
     } catch (IOException e) {
     }
     return decodeStream;
   } catch (IOException e2) {
     throw new RuntimeException(e2);
   } catch (Throwable th) {
     try {
       is.close();
     } catch (IOException e3) {
     }
   }
   return null;
 }
Ejemplo n.º 2
0
 private n<Bitmap> b(i iVar) {
   Object decodeByteArray;
   byte[] bArr = iVar.b;
   Options options = new Options();
   if (this.c == 0 && this.d == 0) {
     options.inPreferredConfig = this.b;
     decodeByteArray = BitmapFactory.decodeByteArray(bArr, 0, bArr.length, options);
   } else {
     options.inJustDecodeBounds = true;
     BitmapFactory.decodeByteArray(bArr, 0, bArr.length, options);
     int i = options.outWidth;
     int i2 = options.outHeight;
     int b = b(this.c, this.d, i, i2);
     int b2 = b(this.d, this.c, i2, i);
     options.inJustDecodeBounds = false;
     options.inSampleSize = a(i, i2, b, b2);
     Bitmap decodeByteArray2 = BitmapFactory.decodeByteArray(bArr, 0, bArr.length, options);
     if (decodeByteArray2 == null
         || (decodeByteArray2.getWidth() <= b && decodeByteArray2.getHeight() <= b2)) {
       Bitmap bitmap = decodeByteArray2;
     } else {
       decodeByteArray = Bitmap.createScaledBitmap(decodeByteArray2, b, b2, true);
       decodeByteArray2.recycle();
     }
   }
   if (decodeByteArray == null) {
     return n.a(new k(iVar));
   }
   return n.a(decodeByteArray, y.a(iVar));
 }
Ejemplo n.º 3
0
  /**
   * 处理大图片工具方法,避免 OOM
   *
   * @param imgPath : 图片路径
   * @return : 返回缩放后的图片
   */
  public static Bitmap zoomBitmap(int width, int height, String imgPath) {

    //  1.获取图片的宽高
    Options options = new BitmapFactory.Options(); // 解析位图的附加条件
    options.inJustDecodeBounds = true; // 只解析位图的头文件信息(图片的附加信息)
    BitmapFactory.decodeFile(imgPath, options);
    int bitmapWidth = options.outWidth;
    int bitmapHeight = options.outHeight;
    //      	System.out.println("图片的宽 = " + bitmapWidth + "   高 = " + bitmapHeight);

    //  2.计算图片的缩放比例
    int dx = bitmapWidth / width;
    int dy = bitmapHeight / height;

    // 计算缩放比例
    int scale = 1;
    if (dx > dy && dy > 1) {
      scale = dx;
      //          System.out.println("按照水平方向绽放,缩放比例 = " + dx);
    }
    if (dy > dx && dx > 1) {
      scale = dy;
      //          System.out.println("按照垂直方法缩放,缩放比例 = " + dy);
    }

    //  3.返回缩放后的位图给调用者
    options.inSampleSize = scale;
    options.inJustDecodeBounds = false; // 解析全部图片
    return BitmapFactory.decodeFile(imgPath, options);
  }
Ejemplo n.º 4
0
  /**
   * Decodes a bitmap from a file containing it minimizing the memory use, known that the bitmap
   * will be drawn in a surface of reqWidth x reqHeight
   *
   * @param srcPath Absolute path to the file containing the image.
   * @param reqWidth Width of the surface where the Bitmap will be drawn on, in pixels.
   * @param reqHeight Height of the surface where the Bitmap will be drawn on, in pixels.
   * @return
   */
  public static Bitmap decodeSampledBitmapFromFile(String srcPath, int reqWidth, int reqHeight) {

    // set desired options that will affect the size of the bitmap
    final Options options = new Options();
    options.inScaled = true;
    options.inPurgeable = true;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
      options.inPreferQualityOverSpeed = false;
    }
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
      options.inMutable = false;
    }

    // make a false load of the bitmap to get its dimensions
    options.inJustDecodeBounds = true;

    BitmapFactory.decodeFile(srcPath, options);

    // calculate factor to subsample the bitmap
    options.inSampleSize = calculateSampleFactor(options, reqWidth, reqHeight);

    // decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeFile(srcPath, options);
  }
Ejemplo n.º 5
0
 public static void decodeBounds(JobContext jc, FileDescriptor fd, Options options) {
   Utils.assertTrue(options != null);
   options.inJustDecodeBounds = true;
   jc.setCancelListener(new DecodeCanceller(options));
   BitmapFactory.decodeFileDescriptor(fd, null, options);
   options.inJustDecodeBounds = false;
 }
Ejemplo n.º 6
0
  /**
   * 处理大图片工具方法,避免 OOM
   *
   * @param imgPath : 图片路径
   * @return : 返回缩放后的图片
   */
  @SuppressWarnings("deprecation")
  public static Bitmap zoomBitmap(Activity activity, String imgPath) {
    //  1. 获取屏幕的宽高信息
    WindowManager windowManager = activity.getWindowManager();
    int width = windowManager.getDefaultDisplay().getWidth();
    int height = windowManager.getDefaultDisplay().getHeight();
    //      	System.out.println("屏幕的宽 = " + width + "   高 = " + height);

    //  2.获取图片的宽高
    Options options = new BitmapFactory.Options(); // 解析位图的附加条件
    options.inJustDecodeBounds = true; // 只解析位图的头文件信息(图片的附加信息)
    BitmapFactory.decodeFile(imgPath, options);
    int bitmapWidth = options.outWidth;
    int bitmapHeight = options.outHeight;
    //      	System.out.println("图片的宽 = " + bitmapWidth + "   高 = " + bitmapHeight);

    //  3.计算图片的缩放比例
    int dx = bitmapWidth / width;
    int dy = bitmapHeight / height;

    int scale = 1;
    if (dx > dy && dy > 1) {
      scale = dx;
      //          System.out.println("按照水平方向绽放,缩放比例 = " + dx);
    }
    if (dy > dx && dx > 1) {
      scale = dy;
      //          System.out.println("按照垂直方法缩放,缩放比例 = " + dy);
    }

    //  4.返回缩放后的位图给调用者
    options.inSampleSize = scale;
    options.inJustDecodeBounds = false; // 解析全部图片
    return BitmapFactory.decodeFile(imgPath, options);
  }
Ejemplo n.º 7
0
  /** 压缩图片 */
  public static Bitmap compressImageFromFile(String srcPath) {
    Options newOpts = new Options();
    newOpts.inJustDecodeBounds = true; // 只读边,不读内容
    Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);

    newOpts.inJustDecodeBounds = false;
    int w = newOpts.outWidth;
    int h = newOpts.outHeight;
    float hh = 800f; //
    float ww = 480f; //
    int be = 1;
    if (w > h && w > ww) {
      be = (int) (newOpts.outWidth / ww);
    } else if (w < h && h > hh) {
      be = (int) (newOpts.outHeight / hh);
    }
    if (be <= 0) be = 1;
    newOpts.inSampleSize = be; // 设置采样率

    newOpts.inPreferredConfig = Config.ARGB_8888; // 该模式是默认的,可不设
    newOpts.inPurgeable = true; // 同时设置才会有效
    newOpts.inInputShareable = true; // 当系统内存不够时候图片自动被回收

    bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
    // return compressBmpFromBmp(bitmap);//原来的方法调用了这个方法企图进行二次压缩
    // 其实是无效的,大家尽管尝试
    return bitmap;
  }
  // 图片按比例大小压缩
  public static Bitmap compress(Bitmap image) {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    image.compress(CompressFormat.JPEG, 100, baos);
    if (baos.toByteArray().length / 1024
        > 1024) { // 判断如果图片大于1M,进行压缩避免在生成图片(BitmapFactory.decodeStream)时溢出
      baos.reset(); // 重置baos即清空baos
      image.compress(CompressFormat.JPEG, 50, baos); // 这里压缩50%,把压缩后的数据存放到baos中
    }
    ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
    Options newOpts = new Options();
    // 开始读入图片,此时把options.inJustDecodeBounds 设回true了
    newOpts.inJustDecodeBounds = true;
    Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
    newOpts.inJustDecodeBounds = false;
    int w = newOpts.outWidth;
    int h = newOpts.outHeight;
    // 现在主流手机比较多是800*480分辨率,所以高和宽我们设置为
    float hh = 800f; // 这里设置高度为800f
    float ww = 480f; // 这里设置宽度为480f
    // 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
    int be = 1; // be=1表示不缩放
    if (w > h && w > ww) { // 如果宽度大的话根据宽度固定大小缩放
      be = (int) (newOpts.outWidth / ww);
    } else if (w < h && h > hh) { // 如果高度高的话根据宽度固定大小缩放
      be = (int) (newOpts.outHeight / hh);
    }
    if (be <= 0) be = 1;
    newOpts.inSampleSize = be; // 设置缩放比例
    // 重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
    isBm = new ByteArrayInputStream(baos.toByteArray());
    bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
    return compressImage(bitmap); // 压缩好比例大小后再进行质量压缩
  }
  // 按大小缩放
  public static Bitmap getImageCompress(final String srcPath) {
    Options newOpts = new Options();
    // 开始读入图片,此时把options.inJustDecodeBounds 设回true了
    newOpts.inJustDecodeBounds = true;
    Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts); // 此时返回bm为空

    newOpts.inJustDecodeBounds = false;
    int w = newOpts.outWidth;
    int h = newOpts.outHeight;
    // 现在主流手机比较多是800*480分辨率,所以高和宽我们设置为
    float hh = 800f; // 这里设置高度为800f
    float ww = 480f; // 这里设置宽度为480f
    // 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
    int be = 1; // be=1表示不缩放
    if (w > h && w > ww) { // 如果宽度大的话根据宽度固定大小缩放
      be = (int) (newOpts.outWidth / ww);
    } else if (w < h && h > hh) { // 如果高度高的话根据宽度固定大小缩放
      be = (int) (newOpts.outHeight / hh);
    }
    if (be <= 0) be = 1;
    newOpts.inSampleSize = be; // 设置缩放比例
    // 重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
    bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
    return compressImage(bitmap); // 压缩好比例大小后再进行质量压缩
  }
Ejemplo n.º 10
0
 public static void decodeBounds(
     JobContext jc, byte[] bytes, int offset, int length, Options options) {
   Utils.assertTrue(options != null);
   options.inJustDecodeBounds = true;
   jc.setCancelListener(new DecodeCanceller(options));
   BitmapFactory.decodeByteArray(bytes, offset, length, options);
   options.inJustDecodeBounds = false;
 }
Ejemplo n.º 11
0
 /**
  * 得到指定大小的 bitmap
  *
  * @param data
  * @param width
  * @param height
  * @return
  */
 public Bitmap getBitmap(byte[] data, int width, int height) {
   Bitmap bitmap = null;
   Options opts = new Options();
   opts.inJustDecodeBounds = true;
   opts.inSampleSize = calculateInSampleSize(opts, width, height);
   opts.inJustDecodeBounds = false;
   bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
   return bitmap;
 }
Ejemplo n.º 12
0
  @SuppressLint("NewApi")
  @Override
  public CustomDrawable doDecode(byte[] bytes, DecodeInfo decodeInfo, UrlSizeKey key, int from) {
    long threadId = Thread.currentThread().getId();
    int viewWidth = key.mViewWidth;
    int viewHeight = key.mViewHeight;
    Options opts = decodeInfo.mBitmapOptions;
    opts.inJustDecodeBounds = true;
    opts.inSampleSize = 1;
    opts.outWidth = -1;
    opts.outHeight = -1;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
      opts.inBitmap = null;
    }
    BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opts);
    int bitmapWidth = opts.outWidth;
    int bitmapHeight = opts.outHeight;
    ImageLoaderLog.d(TAG, key.mUrl);
    ImageLoaderLog.d(TAG, threadId + " bitmap width:" + bitmapWidth + ",height:" + bitmapHeight);
    ImageLoaderLog.d(TAG, threadId + " view width:" + viewWidth + ",height:" + viewHeight);
    if (bitmapWidth <= 0 || bitmapHeight <= 0) {
      return null;
    }
    int sampleSize = getSampleSize(decodeInfo, bitmapWidth, bitmapHeight, viewWidth, viewHeight);
    bitmapWidth /= sampleSize;
    bitmapHeight /= sampleSize;
    ImageLoaderLog.d(TAG, threadId + " sampleSize:" + sampleSize);
    opts.inJustDecodeBounds = false;
    opts.inSampleSize = sampleSize;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
      opts.inMutable = true;
      opts.inBitmap =
          ImageLoader.getInstance().mBitmapPool.get(bitmapWidth, bitmapHeight, false, false);
    }

    Bitmap bm = null;
    try {
      bm = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opts);
      if (sampleSize > 1) {
        saveToDisk(bm, key);
      }
    } catch (Exception e) {
      ImageLoaderLog.d(TAG, threadId + " bitmap decode error");
      e.printStackTrace();
      return null;
    }

    if (bm != null) {
      ImageLoaderLog.d(
          TAG, threadId + " after bitmap width:" + bm.getWidth() + ",height:" + bm.getHeight());
      if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        BitmapLock.lockBitmap(bm);
      }
    }
    BitmapDrawable bd = BitmapDrawableFactory.createBitmapDrawable(bm);
    return bd;
  }
Ejemplo n.º 13
0
 public static long getBitmapSize(String path, Options opts) {
   if (opts == null) {
     opts = new BitmapFactory.Options();
   }
   boolean lastInJustDecodeBounds = opts.inJustDecodeBounds;
   opts.inJustDecodeBounds = true;
   BitmapFactory.decodeFile(path, opts);
   opts.inJustDecodeBounds = lastInJustDecodeBounds;
   return opts.outWidth * opts.outHeight * 4;
 }
Ejemplo n.º 14
0
  public void setData(int requestCode, Intent data) {

    String fileSrc = null;
    if (requestCode == RB_IMAGE_REQUEST_CODE) {
      if ("file".equals(data.getData().getScheme())) {
        // 有些低版本机型返回的Uri模式为file
        fileSrc = data.getData().getPath();
      } else {
        // Uri模型为content
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(data.getData(), proj, null, null, null);
        cursor.moveToFirst();
        int idx = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        fileSrc = cursor.getString(idx);
        cursor.close();
      }
    } else if (requestCode == RB_CAMERA_REQUEST_CODE) {
      fileSrc = pictureFile.getAbsolutePath();
    }
    pictureFile = new File(fileSrc);
    Log.d(TAG, "fileSrc=" + fileSrc);
    // 获取图片的宽和高
    Options options = new Options();
    options.inJustDecodeBounds = true;
    Bitmap img = BitmapFactory.decodeFile(fileSrc, options);

    // 压缩图片
    options.inSampleSize =
        Math.max(
            1,
            (int)
                Math.ceil(
                    Math.max(
                        (double) options.outWidth / 1024f, (double) options.outHeight / 1024f)));
    options.inJustDecodeBounds = false;
    img = BitmapFactory.decodeFile(fileSrc, options);

    // 部分手机会对图片做旋转,这里检测旋转角度
    int degree = ImageTool.readPictureDegree(fileSrc);
    if (degree != 0) {
      // 把图片旋转为正的方向
      img = ImageTool.rotateImage(degree, img);
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    // 可根据流量及网络状况对图片进行压缩
    img.compress(Bitmap.CompressFormat.JPEG, 80, baos);
    // byte[] imgData = baos.toByteArray();

    img_content.setImageBitmap(img);

    Log.d(TAG, img_content.getWidth() + "," + img_content.getHeight());
  }
Ejemplo n.º 15
0
  public static Bitmap decodeFile(
      String path, int dstWidth, int dstHeight, ScalingLogic scalingLogic) {
    Options options = new Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, options);
    options.inJustDecodeBounds = false;
    options.inSampleSize =
        calculateSampleSize(options.outWidth, options.outHeight, dstWidth, dstHeight, scalingLogic);
    Bitmap unscaledBitmap = BitmapFactory.decodeFile(path, options);

    return unscaledBitmap;
  }
Ejemplo n.º 16
0
  public static Bitmap decodeThumbnail(
      JobContext jc, FileDescriptor fd, Options options, int targetSize, int type) {
    if (options == null) options = new Options();
    jc.setCancelListener(new DecodeCanceller(options));

    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFileDescriptor(fd, null, options);
    if (jc.isCancelled()) return null;

    int w = options.outWidth;
    int h = options.outHeight;

    if (type == MediaItem.TYPE_MICROTHUMBNAIL) {
      // We center-crop the original image as it's micro thumbnail. In this case,
      // we want to make sure the shorter side >= "targetSize".
      float scale = (float) targetSize / Math.min(w, h);
      options.inSampleSize = BitmapUtils.computeSampleSizeLarger(scale);

      // For an extremely wide image, e.g. 300x30000, we may got OOM when decoding
      // it for TYPE_MICROTHUMBNAIL. So we add a max number of pixels limit here.
      final int MAX_PIXEL_COUNT = 640000; // 400 x 1600
      if ((w / options.inSampleSize) * (h / options.inSampleSize) > MAX_PIXEL_COUNT) {
        options.inSampleSize =
            BitmapUtils.computeSampleSize(FloatMath.sqrt((float) MAX_PIXEL_COUNT / (w * h)));
      }
    } else {
      // For screen nail, we only want to keep the longer side >= targetSize.
      float scale = (float) targetSize / Math.max(w, h);
      options.inSampleSize = BitmapUtils.computeSampleSizeLarger(scale);
    }

    options.inJustDecodeBounds = false;
    setOptionsMutable(options);

    Bitmap result = BitmapFactory.decodeFileDescriptor(fd, null, options);
    if (result == null) return null;

    // We need to resize down if the decoder does not support inSampleSize
    // (For example, GIF images)
    float scale =
        (float) targetSize
            / (type == MediaItem.TYPE_MICROTHUMBNAIL
                ? Math.min(result.getWidth(), result.getHeight())
                : Math.max(result.getWidth(), result.getHeight()));

    if (scale <= 0.5) result = BitmapUtils.resizeBitmapByScale(result, scale, true);
    return ensureGLCompatibleBitmap(result);
  }
Ejemplo n.º 17
0
  /**
   * @param data 数据或路径
   * @param width 目标宽
   * @param height 目标高
   * @return 图片
   */
  private Bitmap createBitmap(Object data, int width, int height) {
    Options options = new Options();
    int scale = 1;

    if (width > 0 && height > 0) { // 创建目标大小的图片
      options.inJustDecodeBounds = true;
      if (data instanceof String) {
        BitmapFactory.decodeFile((String) data, options);
      } else {
        BitmapFactory.decodeByteArray((byte[]) data, 0, ((byte[]) data).length, options);
      }
      int dw = options.outWidth / width;
      int dh = options.outHeight / height;
      scale = Math.max(dw, dh);
      options = new Options();
    }

    options.inDensity = DeviceInfo.getInstance().getDencity();
    options.inScaled = true;
    options.inPurgeable = true;
    options.inSampleSize = scale;

    Bitmap bitmap = null;
    if (data instanceof String) {
      bitmap = BitmapFactory.decodeFile((String) data, options);
    } else {
      bitmap = BitmapFactory.decodeByteArray((byte[]) data, 0, ((byte[]) data).length, options);
    }
    return bitmap;
  }
  private static Drawable loadDrawableFromStream(
      Context context, String url, String filename, int targetWidth, int targetHeight) {
    prepareResources(context);

    //        Log.v(Constants.LOGTAG,targetWidth);
    //        Log.v(Constants.LOGTAG,targetHeight);
    try {
      Options o = new Options();
      o.inJustDecodeBounds = true;
      FileInputStream stream = new FileInputStream(filename);
      BitmapFactory.decodeStream(stream, null, o);
      stream.close();
      stream = new FileInputStream(filename);
      int scale = 0;
      while ((o.outWidth >> scale) > targetWidth || (o.outHeight >> scale) > targetHeight) {
        Log.v(Constants.LOGTAG, "downsampling");
        scale++;
      }
      o = new Options();
      o.inSampleSize = 1 << scale;
      Bitmap bitmap = BitmapFactory.decodeStream(stream, null, o);
      if (Constants.LOG_ENABLED)
        Log.i(
            Constants.LOGTAG,
            String.format("Loaded bitmap (%dx%d).", bitmap.getWidth(), bitmap.getHeight()));
      BitmapDrawable bd = new BitmapDrawable(mResources, bitmap);
      return new ZombieDrawable(url, bd);
    } catch (IOException e) {
      return null;
    }
  }
Ejemplo n.º 19
0
 /**
  * 从指定路径,按指定宽高比例加载位图
  *
  * @param path
  * @param width
  * @param height
  * @return
  */
 public static Bitmap getBitmap(String path, int width, int height) {
   Bitmap bm = null;
   if (path != null) {
     Options opts = new Options();
     // 只加载边界信息
     opts.inJustDecodeBounds = true;
     BitmapFactory.decodeFile(path, opts);
     // 计算收缩比例
     int x = opts.outWidth / width;
     int y = opts.outHeight / height;
     opts.inSampleSize = x > y ? x : y;
     // 加载全部数据
     opts.inJustDecodeBounds = false;
     bm = BitmapFactory.decodeFile(path, opts);
   }
   return bm;
 }
  public static BitmapSize getBitmapSize(String filePath) {
    Options options = new Options();
    options.inJustDecodeBounds = true;

    BitmapFactory.decodeFile(filePath, options);

    return new BitmapSize(options.outWidth, options.outHeight);
  }
Ejemplo n.º 21
0
 /**
  * 从指定字节数组,按指定宽高比例加载位图
  *
  * @param data
  * @param width
  * @param height
  * @return
  */
 public static Bitmap getBitmap(byte[] data, int width, int height) {
   Bitmap bm = null;
   if (data != null) {
     Options opts = new Options();
     // 只加载边界信息
     opts.inJustDecodeBounds = true;
     BitmapFactory.decodeByteArray(data, 0, data.length, opts);
     // 计算收缩比例
     int x = opts.outWidth / width;
     int y = opts.outHeight / height;
     opts.inSampleSize = x > y ? x : y;
     // 加载全部数据
     opts.inJustDecodeBounds = false;
     bm = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
   }
   return bm;
 }
Ejemplo n.º 22
0
  /**
   * Load bitmap from specified path. If bitmap width or height are bigger then specified then
   * bitmap will be scaled
   *
   * @param path - poster path
   * @param maxWidth - maximum required width
   * @param maxHeight - maximum required height
   * @return loaded scaled bitmap
   */
  public static Bitmap loadScaledBitmap(String path, int maxWidth, int maxHeight, Options options) {
    File file = new File(path);
    if (!file.exists()) {
      Log.w(TAG, "File not found: " + path);
      return null;
    }

    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, options);
    options.inSampleSize = calculateInSampleSize(options, maxWidth, maxHeight);
    options.inJustDecodeBounds = false;
    try {
      return BitmapFactory.decodeFile(path, options);
    } catch (OutOfMemoryError e) {
      Log.e(TAG, "Out of memory");
      return null;
    }
  }
Ejemplo n.º 23
0
  /**
   * Decodes the bitmap from the given byte array if the image size is larger than the given
   * requirement.
   *
   * <p>Note: The returned image may be resized down. However, both width and height must be larger
   * than the <code>targetSize</code>.
   */
  public static Bitmap decodeIfBigEnough(
      JobContext jc, byte[] data, Options options, int targetSize) {
    if (options == null) options = new Options();
    jc.setCancelListener(new DecodeCanceller(options));

    options.inJustDecodeBounds = true;
    BitmapFactory.decodeByteArray(data, 0, data.length, options);
    if (jc.isCancelled()) return null;
    if (options.outWidth < targetSize || options.outHeight < targetSize) {
      return null;
    }
    options.inSampleSize =
        BitmapUtils.computeSampleSizeLarger(options.outWidth, options.outHeight, targetSize);
    options.inJustDecodeBounds = false;
    setOptionsMutable(options);

    return ensureGLCompatibleBitmap(BitmapFactory.decodeByteArray(data, 0, data.length, options));
  }
Ejemplo n.º 24
0
  /**
   * Load the bitmap according form the specified URI.
   *
   * @param uri
   * @return
   */
  private Bitmap loadBitmap(String uri) {
    if (null == uri) {
      return null;
    }

    if (DEBUG) {
      cacheLogD(mIdCache + "  +++ loading new bitmap: " + uri);
    }

    Bitmap btm = null;
    if (uri.startsWith(HEADER_RESOURCE)) {
      String sRes = uri.replaceFirst(HEADER_RESOURCE, "");
      int res;
      try {
        res = Integer.parseInt(sRes);
        return loadBitmap(res);
      } catch (NumberFormatException e) {
        btm = null;
      }
    } else if (uri.startsWith(HEADER_ASSETS)) {
      String path = uri.replace(HEADER_ASSETS, "");
      AssetManager assets = mRes.getAssets();
      try {
        InputStream is = assets.open(path);

        Options options = getOptimizedBitmapOption();
        if (options.inJustDecodeBounds) {
          DebugBitmap.decodeStream(is, null, options, path);
          options.inSampleSize = calculateInSampleSize(options, mMaxWidth, mMaxHeight);
          options.inJustDecodeBounds = false;
        }

        is.close();
        is = assets.open(path);
        btm = DebugBitmap.decodeStream(is, null, options, path);

      } catch (IOException e) {
        e.printStackTrace();
      }

    } else if (uri.startsWith(HEADER_HTTP) || uri.startsWith(HEADER_HTTPS)) {
      btm = requestDownloadBitmap(uri);
    } else if (uri.startsWith(HEADER_FILE) || uri.startsWith(HEADER_FILE_)) {
      String sRes = uri.replaceFirst(HEADER_FILE, "");
      btm = loadImageFromFile(sRes);
    }

    if (null == btm) {
      cacheLogE(mIdCache + " Error loading the resource: " + uri);
      // btm = _defaulResource;
    } else {
      storeBitmap(uri, btm);
    }

    return btm;
  }
Ejemplo n.º 25
0
  public static void copyImageFromAsset(Context context, String fileName, String filePath) {

    File fileDir = new File(filePath);
    if (!fileDir.exists()) {
      fileDir.mkdirs();
    }

    String wholePath;
    if (filePath.endsWith("/")) {
      wholePath = filePath + fileName;
    } else {
      wholePath = filePath + "/" + fileName;
    }

    File file = new File(wholePath);

    if (file.exists()) {
      // 如果文件存在,检测是否复制成功
      Options myOptions = new Options();
      myOptions.inJustDecodeBounds = true;
      BitmapFactory.decodeFile(wholePath, myOptions);
      if (myOptions.outWidth > 0 && myOptions.outHeight > 0) {
        return;
      }
    }

    // 若文件不存在,则copy
    AssetManager am = context.getAssets();
    InputStream is;
    FileOutputStream fos;
    try {
      is = am.open(fileName);
      fos = new FileOutputStream(wholePath);

      int bytesRead;
      byte[] buf = new byte[4 * 1024];
      while ((bytesRead = is.read(buf)) != -1) {
        fos.write(buf, 0, bytesRead);
      }

      fos.flush();
      fos.close();
      is.close();

    } catch (Exception e) {
      e.printStackTrace();
      return;
    }

    is = null;
    am = null;
    fos = null;
    System.gc();
  }
Ejemplo n.º 26
0
  private Bitmap loadImageFromFile(String file) {
    Options options = getOptimizedBitmapOption();
    if (options.inJustDecodeBounds) {
      BitmapFactory.decodeFile(file, options);
      options.inSampleSize = calculateInSampleSize(options, mMaxWidth, mMaxHeight);
      options.inJustDecodeBounds = false;
    }

    Bitmap btm = DebugBitmap.decodeFile(file, options);
    return btm;
  }
Ejemplo n.º 27
0
  /**
   * 根据url下载图片在指定的文件
   *
   * @param urlStr
   * @param file
   * @return
   */
  public static Bitmap downloadImgByUrl(String urlStr, ImageView imageview) {
    FileOutputStream fos = null;
    InputStream is = null;
    try {
      URL url = new URL(urlStr);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      is = new BufferedInputStream(conn.getInputStream());
      is.mark(is.available());

      Options opts = new Options();
      opts.inJustDecodeBounds = true;
      Bitmap bitmap = BitmapFactory.decodeStream(is, null, opts);

      // 获取imageview想要显示的宽和高
      ImageSize imageViewSize = ImageSizeUtil.getImageViewSize(imageview);
      opts.inSampleSize =
          ImageSizeUtil.caculateInSampleSize(opts, imageViewSize.width, imageViewSize.height);

      opts.inJustDecodeBounds = false;
      is.reset();
      bitmap = BitmapFactory.decodeStream(is, null, opts);

      conn.disconnect();
      return bitmap;

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        if (is != null) is.close();
      } catch (IOException e) {
      }

      try {
        if (fos != null) fos.close();
      } catch (IOException e) {
      }
    }

    return null;
  }
  private static Bitmap decodeSampledBitmapFromUrl(String url, int reqWidth, int reqHeight)
      throws IOException {

    // First decode with inJustDecodeBounds=true to check dimensions
    final Options options = new Options();
    options.inJustDecodeBounds = true;

    InputStream stream = fetchStream(url);
    BitmapFactory.decodeStream(stream, null, options);
    stream.close();

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;

    stream = fetchStream(url);
    Bitmap bitmap = BitmapFactory.decodeStream(stream, null, options);
    stream.close();

    return bitmap;
  }
Ejemplo n.º 29
0
  public static Bitmap loadScaledBitmap(
      ContentResolver resolver, Uri uri, int maxWidth, int maxHeight, Options options) {

    options.inSampleSize = calculateInSampleSize(options, maxWidth, maxHeight);
    options.inJustDecodeBounds = false;
    try {
      return BitmapFactory.decodeStream(resolver.openInputStream(uri), null, options);
    } catch (OutOfMemoryError e) {
      Log.e(TAG, "Out of memory");
    } catch (FileNotFoundException e) {
      Log.e(TAG, "File not found: " + uri);
    }
    return null;
  }
Ejemplo n.º 30
0
 private void copyOptions(Options srcOptions, Options destOptions) {
   destOptions.inDensity = srcOptions.inDensity;
   destOptions.inDither = srcOptions.inDither;
   destOptions.inInputShareable = srcOptions.inInputShareable;
   destOptions.inJustDecodeBounds = srcOptions.inJustDecodeBounds;
   destOptions.inPreferredConfig = srcOptions.inPreferredConfig;
   destOptions.inPurgeable = srcOptions.inPurgeable;
   destOptions.inSampleSize = srcOptions.inSampleSize;
   destOptions.inScaled = srcOptions.inScaled;
   destOptions.inScreenDensity = srcOptions.inScreenDensity;
   destOptions.inTargetDensity = srcOptions.inTargetDensity;
   destOptions.inTempStorage = srcOptions.inTempStorage;
   if (Build.VERSION.SDK_INT >= 10) copyOptions10(srcOptions, destOptions);
   if (Build.VERSION.SDK_INT >= 11) copyOptions11(srcOptions, destOptions);
 }