Esempio 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;
 }
Esempio n. 2
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;
  }
Esempio n. 3
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);
  }
Esempio n. 4
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));
 }
Esempio n. 5
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);
  }
  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;
    }
  }
Esempio n. 7
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;
  }
Esempio n. 8
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;
  }
Esempio n. 9
0
  protected Options prepareDecodingOptions(ImageSize imageSize, ImageDecodingInfo decodingInfo) {
    ImageScaleType scaleType = decodingInfo.getImageScaleType();
    int scale;
    if (scaleType == ImageScaleType.NONE) {
      scale = ImageSizeUtils.computeMinImageSampleSize(imageSize);
    } else {
      ImageSize targetSize = decodingInfo.getTargetSize();
      boolean powerOf2 = scaleType == ImageScaleType.IN_SAMPLE_POWER_OF_2;
      scale =
          ImageSizeUtils.computeImageSampleSize(
              imageSize, targetSize, decodingInfo.getViewScaleType(), powerOf2);
    }
    if (scale > 1 && loggingEnabled) {
      L.d(
          LOG_SABSAMPLE_IMAGE,
          imageSize,
          imageSize.scaleDown(scale),
          scale,
          decodingInfo.getImageKey());
    }

    Options decodingOptions = decodingInfo.getDecodingOptions();
    decodingOptions.inSampleSize = scale;
    return decodingOptions;
  }
Esempio n. 10
0
 protected Options prepareDecodingOptions(ImageSize imageSize, ImageDecodingInfo decodingInfo) {
   int scale;
   ImageScaleType scaleType = decodingInfo.getImageScaleType();
   if (scaleType == ImageScaleType.NONE) {
     scale = 1;
   } else if (scaleType == ImageScaleType.NONE_SAFE) {
     scale = ImageSizeUtils.computeMinImageSampleSize(imageSize);
   } else {
     boolean powerOf2;
     ImageSize targetSize = decodingInfo.getTargetSize();
     if (scaleType == ImageScaleType.IN_SAMPLE_POWER_OF_2) {
       powerOf2 = true;
     } else {
       powerOf2 = false;
     }
     scale =
         ImageSizeUtils.computeImageSampleSize(
             imageSize, targetSize, decodingInfo.getViewScaleType(), powerOf2);
   }
   if (scale > 1 && this.loggingEnabled) {
     C0126L.m33d(
         LOG_SUBSAMPLE_IMAGE,
         imageSize,
         imageSize.scaleDown(scale),
         Integer.valueOf(scale),
         decodingInfo.getImageKey());
   }
   Options decodingOptions = decodingInfo.getDecodingOptions();
   decodingOptions.inSampleSize = scale;
   return decodingOptions;
 }
  // 图片按比例大小压缩
  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); // 压缩好比例大小后再进行质量压缩
  }
Esempio n. 13
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);
  }
Esempio n. 14
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);
  }
Esempio n. 15
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;
 }
Esempio n. 16
0
 /**
  * 从指定路径,按指定收缩比例加载位图
  *
  * @param path
  * @param scale
  * @return
  */
 public static Bitmap getBitmap(String path, int scale) {
   Bitmap bm = null;
   if (path != null) {
     Options opts = new Options();
     opts.inSampleSize = scale;
     bm = BitmapFactory.decodeFile(path, opts);
   }
   return bm;
 }
Esempio n. 17
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;
  }
Esempio n. 18
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;
  }
  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());
  }
Esempio n. 20
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;
  }
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_FROM_CAMERA && resultCode == RESULT_OK) {
      InputStream is = null;
      try {
        is = new FileInputStream(imageFileLocation);
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      }
      if (is == null) {
        try {
          Uri u = data.getData();
          is = getContentResolver().openInputStream(u);
        } catch (FileNotFoundException e) {
          e.printStackTrace();
        }
      }
      try {
        Options opt = new BitmapFactory.Options();
        opt.inTempStorage = new byte[16 * 1024];
        opt.inSampleSize = 6;
        Bitmap imageBitmap = BitmapFactory.decodeStream(is, new Rect(), opt);
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        imageBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bao);
        System.out.println(bao.size());
        imgData = new byte[bao.size()];
        imgData = bao.toByteArray();
        if (is != null) {
          is.close();
        }
        if (bao != null) {
          bao.close();
        }

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

      if (isOnline()) {
        new UploadTask().execute();
      } else {
        _sinDTO.setChannelId(_journey.getChannelId());
        _sinDTO.setLongitude(String.valueOf(lng));
        _sinDTO.setLatitude(String.valueOf(lat));
        _sinDTO.setPicData(imgData);
        insertedId = dbs.insert(_sinDTO);
        showMessage("Foto tersimpan di local, karena tidak terdapat koneksi internet");
      }
    }
  }
Esempio n. 22
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;
  }
Esempio n. 23
0
 @Override
 public SizeDrawable getSize(byte[] bytes, DecodeInfo decodeInfo) {
   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;
   return new SizeDrawable(bitmapWidth, bitmapHeight);
 }
Esempio n. 24
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);
 }
Esempio n. 25
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;
 }
Esempio n. 26
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;
 }
Esempio n. 27
0
  /**
   * 功能简述:根据指定的图片文件的uri,创建图片。 功能详细描述: 注意:
   *
   * @param context
   * @param uri:目标图片文件的uri
   * @return
   */
  public static Bitmap loadBitmap(Context context, Uri uri, int simpleSize) {
    Bitmap pRet = null;
    if (null == context) {
      Log.i(TAG, "load bitmap context is null");
      return pRet;
    }
    if (null == uri) {
      Log.i(TAG, "load bitmap uri is null");
      return pRet;
    }

    InputStream is = null;
    int sampleSize = simpleSize;
    Options opt = new Options();

    boolean bool = true;
    while (bool) {
      try {
        is = context.getContentResolver().openInputStream(uri);
        opt.inSampleSize = sampleSize;
        pRet = null;
        pRet = BitmapFactory.decodeStream(is, null, opt);
        bool = false;
      } catch (OutOfMemoryError e) {
        sampleSize *= 2;
        if (sampleSize > (1 << 10)) {
          bool = false;
        }
      } catch (Throwable e) {
        bool = false;
        Log.i(TAG, e.getMessage());
      } finally {
        try {
          if (is != null) {
            is.close();
          }
        } catch (Exception e2) {
          Log.i(TAG, e2.getMessage());
          Log.i(TAG, "load bitmap close uri stream exception");
        }
      }
    }

    return pRet;
  }
Esempio n. 28
0
  private Bitmap loadBitmap(int id) {
    String key = normalizeURI(id);
    Bitmap btm = mBitmapContainer.get(key);
    if (null != btm) {
      return (btm);
    }

    Options options = getOptimizedBitmapOption();
    if (options.inJustDecodeBounds) {
      BitmapFactory.decodeResource(mRes, id, options);
      options.inSampleSize = calculateInSampleSize(options, mMaxWidth, mMaxHeight);
      options.inJustDecodeBounds = false;
    }

    btm = DebugBitmap.decodeResource(mRes, id, options);

    return storeBitmap(key, btm);
  }
Esempio n. 29
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;
    }
  }
Esempio n. 30
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));
  }