Example #1
1
  public static void resizeRotateAndSaveByteArrayToSDCardPath(
      String desiredName, byte[] data, float targetWidth, float targetHeight) {
    /** GET bitmap info * */
    BitmapFactory.Options opts = new Options();
    opts.inJustDecodeBounds = true;
    BitmapFactory.decodeByteArray(data, 0, data.length, opts);

    /** scale approximately * */
    opts.inJustDecodeBounds = false;
    opts.inSampleSize =
        calculateInSampleSize(opts, Math.round(targetWidth), Math.round(targetHeight));
    Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
    data = null;

    /** calculate final WIDTH and HEIGHT (with right aspect ratio) * */
    int originalWidth = bmp.getWidth();
    int originalHeight = bmp.getHeight();
    float scale = (float) targetWidth / (float) originalWidth;
    int newWidth = Math.round(targetWidth);
    int newHeight = Math.round(scale * (float) originalHeight);

    /** resize exactly to desired size * */
    Bitmap scaledBmp = Bitmap.createScaledBitmap(bmp, newWidth, newHeight, true);
    /** rotating * */
    Matrix mtx = new Matrix();
    mtx.preRotate(90);
    /** saving * */
    saveToSDCardPath(
        desiredName,
        Bitmap.createBitmap(
            scaledBmp, 0, 0, scaledBmp.getWidth(), scaledBmp.getHeight(), mtx, true));
  }
Example #2
1
 /**
  * Deposit in the province read images, width is high, the greater the picture clearer, but also
  * the memory
  *
  * @param imagePath Pictures in the path of the memory card
  * @param maxWidth The highest limit value target width
  * @param maxHeight The highest limit value target height
  * @return
  */
 public Bitmap readImage(String imagePath, int maxWidth, int maxHeight) {
   File imageFile = new File(imagePath);
   if (imageFile.exists()) {
     try {
       BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(imageFile));
       BitmapFactory.Options options = new BitmapFactory.Options();
       options.inJustDecodeBounds = true;
       BitmapFactory.decodeStream(inputStream, null, options);
       inputStream.close();
       int i = 0;
       while (true) {
         if ((options.outWidth >> i <= maxWidth) && (options.outHeight >> i <= maxHeight)) {
           inputStream = new BufferedInputStream(new FileInputStream(new File(imagePath)));
           options.inSampleSize = (int) Math.pow(2.0, i);
           options.inJustDecodeBounds = false;
           Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, options);
           inputStream.close();
           return bitmap;
         }
         i += 1;
       }
     } catch (IOException e) {
       Logger.e("This path does not exist" + imagePath, e);
     }
   }
   return null;
 }
Example #3
0
  private void setPic() {
    // Get the dimensions of the View
    int targetW = mImageView.getWidth();
    int targetH = mImageView.getHeight();

    // Get the dimensions of the bitmap
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bmOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
    int photoW = bmOptions.outWidth;
    int photoH = bmOptions.outHeight;

    // Determine how much to scale down the image
    int scaleFactor = Math.min(photoW / targetW, photoH / targetH);

    // Decode the image file into a Bitmap sized to fill the View
    bmOptions.inJustDecodeBounds = false;
    bmOptions.inSampleSize = scaleFactor;
    bmOptions.inPurgeable = true;

    Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
    mImageView.setImageBitmap(bitmap);

    Intent intent = new Intent(this, CropImageActivity.class);
    //        intent.putExtra("bitmap", bitmap);
    MyApplication application = (MyApplication) getApplication();
    application.mBitmap = bitmap;
    startActivity(intent);

    String directoryDcim = Environment.DIRECTORY_DCIM;
  }
 /**
  * 获取指定路径下的图片的指定大小的缩略图 getImageThumbnail
  *
  * @return Bitmap
  * @throws
  */
 public static Bitmap getImageThumbnail(String imagePath, int width, int height) {
   Bitmap bitmap = null;
   BitmapFactory.Options options = new BitmapFactory.Options();
   options.inJustDecodeBounds = true;
   // 获取这个图片的宽和高,注意此处的bitmap为null
   bitmap = BitmapFactory.decodeFile(imagePath, options);
   options.inJustDecodeBounds = false; // 设为 false
   // 计算缩放比
   int h = options.outHeight;
   int w = options.outWidth;
   int beWidth = w / width;
   int beHeight = h / height;
   int be = 1;
   if (beWidth < beHeight) {
     be = beWidth;
   } else {
     be = beHeight;
   }
   if (be <= 0) {
     be = 1;
   }
   options.inSampleSize = be;
   // 重新读入图片,读取缩放后的bitmap,注意这次要把options.inJustDecodeBounds 设为 false
   bitmap = BitmapFactory.decodeFile(imagePath, options);
   // 利用ThumbnailUtils来创建缩略图,这里要指定要缩放哪个Bitmap对象
   bitmap =
       ThumbnailUtils.extractThumbnail(
           bitmap, width, height, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
   return bitmap;
 }
Example #5
0
  /**
   * Decode and sample down a bitmap from a file to the requested width and height.
   *
   * @param filename The full path of the file to decode
   * @param reqWidth The requested width of the resulting bitmap
   * @param reqHeight The requested height of the resulting bitmap
   * @param cache The ImageCache used to find candidate bitmaps for use with inBitmap
   * @return A bitmap sampled down from the original with the same aspect ratio and dimensions that
   *     are equal to or greater than the requested width and height
   */
  public static Bitmap decodeSampledBitmapFromUri(
      Context context, Uri fileuri, int reqWidth, int reqHeight, ImageCache cache) {

    Bitmap bm = null;

    try {
      // First decode with inJustDecodeBounds=true to check dimensions
      final BitmapFactory.Options options = new BitmapFactory.Options();
      options.inJustDecodeBounds = true;
      BitmapFactory.decodeStream(
          context.getContentResolver().openInputStream(fileuri), null, options);

      // Calculate inSampleSize
      options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

      // Decode bitmap with inSampleSize set
      options.inJustDecodeBounds = false;
      bm =
          BitmapFactory.decodeStream(
              context.getContentResolver().openInputStream(fileuri), null, options);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }

    return bm;
  }
Example #6
0
 // 同比缩放解决方案---图片按比例大小压缩方法(根据Bitmap图片压缩)
 public static Bitmap compressByBitmap(
     Bitmap srcBitmap, int dstWidth, int dstHeight, int sizeInKb, ScalingLogic scalingLogic) {
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   srcBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
   int quality = 100;
   while (baos.toByteArray().length / 1024
       > 1024) { // 判断如果图片大于1M,进行压缩避免在生成图片(BitmapFactory.decodeStream)时溢出
     baos.reset(); // 重置baos即清空baos
     srcBitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos); // 这里压缩quality%,把压缩后的数据存放到baos中
     quality -= 10; // 每次都减少10
   }
   ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
   BitmapFactory.Options options = new BitmapFactory.Options();
   // 开始读入图片,此时把options.inJustDecodeBounds 设回true了
   options.inJustDecodeBounds = true;
   Bitmap bitmap = BitmapFactory.decodeStream(bais, null, options);
   int inSampleSize =
       calculateSampleSize(options.outWidth, options.outHeight, dstWidth, dstHeight, scalingLogic);
   options.inSampleSize = inSampleSize > 0 ? inSampleSize : 1; // 设置缩放比例
   options.inJustDecodeBounds = false;
   options.inPreferredConfig = Bitmap.Config.RGB_565;
   options.inPurgeable = true;
   options.inInputShareable = true;
   // 重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
   bais = new ByteArrayInputStream(baos.toByteArray());
   bitmap = BitmapFactory.decodeStream(bais, null, options);
   return compressImage(bitmap, sizeInKb); // 压缩好比例大小后再进行质量压缩
 }
Example #7
0
  /**
   * 通过压缩图片的尺寸来压缩图片大小,通过读入流的方式,可以有效防止网络图片数据流形成位图对象时内存过大的问题;
   *
   * @param InputStream 要压缩图片,以流的形式传入
   * @param targetWidth 缩放的目标宽度
   * @param targetHeight 缩放的目标高度
   * @return 缩放后的图片
   * @throws IOException 读输入流的时候发生异常
   */
  public static Bitmap compressBySize(InputStream is, int targetWidth, int targetHeight)
      throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buff = new byte[1024];
    int len = 0;
    while ((len = is.read(buff)) != -1) {
      baos.write(buff, 0, len);
    }

    byte[] data = baos.toByteArray();
    BitmapFactory.Options opts = new BitmapFactory.Options();
    opts.inJustDecodeBounds = true;
    Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
    // 得到图片的宽度、高度;
    int imgWidth = opts.outWidth;
    int imgHeight = opts.outHeight;
    // 分别计算图片宽度、高度与目标宽度、高度的比例;取大于该比例的最小整数;
    int widthRatio = (int) Math.ceil(imgWidth / (float) targetWidth);
    int heightRatio = (int) Math.ceil(imgHeight / (float) targetHeight);
    if (widthRatio > 1 && widthRatio > 1) {
      if (widthRatio > heightRatio) {
        opts.inSampleSize = widthRatio;
      } else {
        opts.inSampleSize = heightRatio;
      }
    }
    // 设置好缩放比例后,加载图片进内存;
    opts.inJustDecodeBounds = false;
    bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
    return bitmap;
  }
Example #8
0
  /**
   * Decode and sample down a bitmap from resources to the requested width and height.
   *
   * @param res The resources object containing the image data
   * @param resId The resource id of the image data
   * @param reqWidth The requested width of the resulting bitmap
   * @param reqHeight The requested height of the resulting bitmap
   * @param cache The ImageCache used to find candidate bitmaps for use with inBitmap
   * @return A bitmap sampled down from the original with the same aspect ratio and dimensions that
   *     are equal to or greater than the requested width and height
   */
  public static Bitmap decodeSampledBitmapFromResource(
      Resources res,
      int resId,
      int reqWidth,
      int reqHeight,
      com.qicheng.business.ui.chat.utils.video.ImageCache cache) {

    // BEGIN_INCLUDE (read_bitmap_dimensions)
    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    // END_INCLUDE (read_bitmap_dimensions)

    // If we're running on Honeycomb or newer, try to use inBitmap
    if (Utils.hasHoneycomb()) {
      addInBitmapOptions(options, cache);
    }

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
  }
Example #9
0
  public void setBackground() {
    // avoid outOfMemory problem
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;

    BitmapFactory.decodeResource(this.getResources(), R.drawable.background, options);

    int width = options.outWidth;
    int height = options.outHeight;

    Display display = getWindowManager().getDefaultDisplay();

    int screenWidth = display.getWidth();
    int screenHeight = display.getHeight();

    int scale = 1;
    int scaleWeight = width / screenWidth;
    int scaleHeight = height / screenHeight;

    if (scaleWeight >= scaleHeight && scaleWeight > 1) {
      scale = scaleWeight;
    } else if (scaleHeight > scaleWeight && scaleHeight >= 1) {
      scale = scaleHeight;
    }

    options.inSampleSize = 4;
    options.inJustDecodeBounds = false;
    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.background, options);

    rl.setBackground(new BitmapDrawable(getResources(), bitmap));
  }
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);

    if (resultCode == RESULT_OK) {
      Uri imageFileUri = intent.getData();
      try {
        BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
        bmpFactoryOptions.inJustDecodeBounds = true;
        bmp =
            BitmapFactory.decodeStream(
                getContentResolver().openInputStream(imageFileUri), null, bmpFactoryOptions);

        bmpFactoryOptions.inJustDecodeBounds = false;
        bmp =
            BitmapFactory.decodeStream(
                getContentResolver().openInputStream(imageFileUri), null, bmpFactoryOptions);

        alteredBitmap =
            Bitmap.createBitmap(drawingArea.getWidth(), drawingArea.getHeight(), bmp.getConfig());

        canvas = new Canvas(alteredBitmap);
        paint = new Paint();
        paint.setColor(Color.GREEN);
        paint.setStrokeWidth(5);
        matrix = new Matrix();
        canvas.drawBitmap(bmp, matrix, paint);

        drawingArea.cache = alteredBitmap;

      } catch (Exception e) {
        Log.v("ERROR", e.toString());
      }
    }
  }
  /**
   * 按指定图片大小返回压缩参数
   *
   * @param pathName
   * @param maxWidth
   * @param maxHeight
   * @return
   */
  public static BitmapFactory.Options createOptions(String pathName, int maxWidth, int maxHeight) {
    BitmapFactory.Options opts = new BitmapFactory.Options();
    opts.inJustDecodeBounds = true;
    // 当opts不为null时,但decodeFile返回空,不为图片分配内存,只获取图片的大小,并保存在opts的outWidth和outHeight
    BitmapFactory.decodeFile(pathName, opts);

    int srcWidth = opts.outWidth;
    int srcHeight = opts.outHeight;
    int destWidth = 0;
    int destHeight = 0;
    // 缩放的比例
    double ratio = 0.0;
    // 按比例计算缩放后的图片大小,maxLength是长或宽允许的最大长度
    if (srcWidth > srcHeight) {
      ratio = srcWidth / maxWidth;
      destWidth = maxWidth;
      destHeight = (int) (srcHeight / ratio);
    } else {
      ratio = srcHeight / maxHeight;
      destHeight = maxHeight;
      destWidth = (int) (srcWidth / ratio);
    }
    // 对图片进行压缩,是在读取的过程中进行压缩,而不是把图片读进了内存再进行压缩
    BitmapFactory.Options newOpts = new BitmapFactory.Options();
    // 缩放的比例,缩放是很难按准备的比例进行缩放的,目前我只发现只能通过inSampleSize来进行缩放,其值表明缩放的倍数,SDK中建议其值是2的指数值
    newOpts.inSampleSize = (int) ratio + 1;
    // inJustDecodeBounds设为false表示把图片读进内存中
    newOpts.inJustDecodeBounds = false;
    // 设置大小,这个一般是不准确的,是以inSampleSize的为准,但是如果不设置却不能缩放
    newOpts.outHeight = destHeight;
    newOpts.outWidth = destWidth;
    return newOpts;
  }
Example #12
0
 /**
  * 获取最大图片不能超过该值
  *
  * @param context
  * @param path
  * @param nWidth
  * @return
  */
 public static Bitmap ReadFileToMaxBitmap(Context context, String path, int nWidth) {
   try {
     BitmapFactory.Options options = new BitmapFactory.Options();
     options.inSampleSize = 1;
     options.inJustDecodeBounds = true;
     // options.outWidth=40;
     BitmapFactory.decodeFile(path, options);
     if (nWidth < options.outWidth) {
       if (options.outHeight > options.outWidth) {
         // nWidth = options.outHeight / nWidth;
         if (options.outHeight % nWidth == 0) {
           nWidth = options.outHeight / nWidth;
         } else {
           nWidth = options.outHeight / nWidth + 1;
         }
       } else {
         if (options.outWidth % nWidth == 0) {
           nWidth = options.outWidth / nWidth;
         } else {
           nWidth = options.outWidth / nWidth + 1;
         }
       }
       options.inSampleSize = nWidth;
     }
     options.inJustDecodeBounds = false;
     Bitmap bmp = BitmapFactory.decodeFile(path, options);
     return bmp;
   } catch (Exception e) {
     e.printStackTrace();
   }
   return null;
 }
 private void saveImage(byte[] data) {
   try {
     BitmapFactory.Options opts = new BitmapFactory.Options();
     opts.inJustDecodeBounds = true;
     BitmapFactory.decodeByteArray(data, 0, data.length, opts);
     DisplayMetrics dm = new DisplayMetrics();
     getWindowManager().getDefaultDisplay().getMetrics(dm);
     opts.inSampleSize = calculateInSampleSize(opts, dm.heightPixels, dm.widthPixels);
     opts.inPurgeable = true;
     opts.inInputShareable = true;
     opts.inTempStorage = new byte[64 * 1024];
     opts.inJustDecodeBounds = false;
     Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
     if (bm != null) {
       bm = Util.rotate(bm, getRotate());
       File file = new File(filePath);
       BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
       bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
       bos.flush();
       bos.close();
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Example #14
0
  private Bitmap getBitmap(String path, boolean isLargeFlg) {

    // 先解析图片边框的大小
    BitmapFactory.Options ops = new BitmapFactory.Options();
    ops.inJustDecodeBounds = true;
    Bitmap bm = BitmapFactory.decodeFile(path, ops);
    ops.inSampleSize = 1;
    int oHeight = ops.outHeight;
    int oWidth = ops.outWidth;

    // 控制压缩比
    int contentHeight = 0;
    int contentWidth = 0;
    contentWidth = 400;
    contentHeight = 800;
    //        if(isLargeFlg){
    //        }else{
    //            contentHeight = ITEM_HEIGHT;
    //            contentWidth = ITEM_WIDTH;
    //        }
    if (((float) oHeight / contentHeight) < ((float) oWidth / contentWidth)) {
      ops.inSampleSize = (int) Math.ceil((float) oWidth / contentWidth);
    } else {
      ops.inSampleSize = (int) Math.ceil((float) oHeight / contentHeight);
    }
    ops.inJustDecodeBounds = false;
    bm = BitmapFactory.decodeFile(path, ops);
    return bm;
  }
Example #15
0
  /**
   * @param is image input stream
   * @return sampling factor
   * @throws IOException if error happens
   */
  private int resolveSampleFactor(final InputStream is, final BitmapFactory.Options options)
      throws IOException {
    if (!is.markSupported()) {
      throw new IllegalStateException("Input stream does not support marks!");
    }

    options.inJustDecodeBounds = true;
    int result = 1;
    try {

      MarkableInputStream markableStream = new MarkableInputStream(is); // Thanks to Square guys :)
      long mark = markableStream.savePosition(BOUNDS_INFO_MARK);
      doStreamDecode(markableStream, options);

      result =
          ImagesManager.calculateSampleFactor(
              options.outWidth, options.outHeight, getRequiredWidth(), getRequiredHeight());

      markableStream.reset(mark);

    } finally {
      options.inJustDecodeBounds = false;
    }
    return result;
  }
  public static int computeSampleSize(
      BitmapFactory.Options options, String path, int minSideLength, int maxNumOfPixels) {
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, options);

    if (options.outWidth != -1) {
      options.inJustDecodeBounds = false;

      int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);

      int roundedSize;
      if (initialSize <= 8) {
        roundedSize = 1;
        while (roundedSize < initialSize) {
          roundedSize <<= 1;
        }
      } else {
        roundedSize = (initialSize + 7) / 8 * 8;
      }

      options.inSampleSize = roundedSize;

      return roundedSize;
    } else {
      return -1;
    }
  }
  private Bitmap handleImage(String imagePath) {
    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
    bitmapOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(imagePath, bitmapOptions);

    // set bitmap options to scale the image decode target
    bitmapOptions.inJustDecodeBounds = false;
    bitmapOptions.inSampleSize = 4;
    bitmapOptions.inPurgeable = true;

    // decode the JPEG file into a bitmap
    Bitmap originalBitmap = null;
    Bitmap bitmap = null;
    try {
      originalBitmap = BitmapFactory.decodeFile(imagePath, bitmapOptions);
      bitmap = BitmapScaler.scaleToFill(originalBitmap, mImageSize, mImageSize);
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    } finally {
      if (originalBitmap != null) originalBitmap.recycle();
    }

    // handle bitmap rotation
    int rotation = getBitmapRotation(imagePath);
    if (rotation > 0) {
      Matrix matrix = new Matrix();
      matrix.setRotate(rotation, (float) bitmap.getWidth() / 2, (float) bitmap.getHeight() / 2);
      bitmap =
          Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }

    return bitmap;
  }
 public static boolean compressBitmapFile(
     String dstPath, String srcPath, int reqWidth, int reqHeight) {
   final BitmapFactory.Options options = new BitmapFactory.Options();
   options.inJustDecodeBounds = true;
   options.inPurgeable = true;
   BitmapFactory.decodeFile(srcPath, options);
   if (options.outWidth > 0) {
     if (options.outWidth > reqWidth || options.outHeight > reqHeight) {
       options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
       options.inJustDecodeBounds = false;
       try {
         Bitmap bmp = BitmapFactory.decodeFile(srcPath, options);
         FileHelper.saveBitmapToFile(dstPath, bmp, 90);
       } catch (OutOfMemoryError e) {
         e.printStackTrace();
         return false;
       }
     } else {
       FileHelper.copyFile(dstPath, srcPath);
     }
   } else {
     return false;
   }
   return true;
 }
Example #19
0
  public static Bitmap imageZoomByScreen(Context context, String uri) {
    int degree = readPictureDegree(uri);
    Bitmap bm;
    BitmapFactory.Options opt = new BitmapFactory.Options();
    // 这个isjustdecodebounds很重要
    opt.inJustDecodeBounds = true;
    bm = BitmapFactory.decodeFile(uri, opt);
    // 获取到这个图片的原始宽度和高度
    int picWidth = opt.outWidth;
    int picHeight = opt.outHeight;

    // 获取屏的宽度和高度
    int screenWidth =
        com.aosijia.dragonbutler.imagegroup.utils.DisplayUtils.getScreenWidth(context);
    int screenHeight =
        com.aosijia.dragonbutler.imagegroup.utils.DisplayUtils.getScreenHeight(context);

    // isSampleSize是表示对图片的缩放程度,比如值为2图片的宽度和高度都变为以前的1/2
    opt.inSampleSize = 1;
    // 根据屏的大小和图片大小计算出缩放比例
    if (picWidth > picHeight) {
      if (picWidth > screenWidth) opt.inSampleSize = picWidth / screenWidth;
    } else {
      if (picHeight > screenHeight) opt.inSampleSize = picHeight / screenHeight;
    }

    // 这次再真正地生成一个有像素的,经过缩放了的bitmap
    opt.inJustDecodeBounds = false;
    bm = BitmapFactory.decodeFile(uri, opt);
    bm = rotateBitmap(bm, degree);
    return bm;
  }
  public static Bitmap LoadBackgroundBitmap(Context context, int id)
      throws Exception, OutOfMemoryError {
    Display display =
        ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
    int displayWidth = display.getWidth();
    int displayHeight = display.getHeight();

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inPreferredConfig = Config.RGB_565;
    options.inJustDecodeBounds = true;

    float widthScale = options.outWidth / displayWidth;
    float heightScale = options.outHeight / displayHeight;
    float scale = widthScale > heightScale ? widthScale : heightScale;

    if (scale >= 8) options.inSampleSize = 8;
    else if (scale >= 6) options.inSampleSize = 6;
    else if (scale >= 4) options.inSampleSize = 4;
    else if (scale >= 2) options.inSampleSize = 2;
    else options.inSampleSize = 1;

    options.inJustDecodeBounds = false;

    return BitmapFactory.decodeResource(context.getResources(), id, options);
  }
Example #21
0
  // 图片压缩
  private Bitmap compressImageFromFile(String srcPath) {
    BitmapFactory.Options newOpts = new BitmapFactory.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;
  }
Example #22
0
  Bitmap scaleToDPSize(File file, int targetW, int targetH) {

    // Scale The Image

    // Get the dimensions of the bitmap
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bmOptions.inJustDecodeBounds = true;

    BitmapFactory.decodeFile(file.getAbsolutePath(), bmOptions);
    int photoW = bmOptions.outWidth;
    int photoH = bmOptions.outHeight;

    if (photoH < 150 || photoW < 100) {
      Toast.makeText(this, "Image Resolution is too small.", Toast.LENGTH_SHORT).show();
      return null;
    }

    // Determine how much to scale down the image
    int scaleFactor = Math.min(photoW / targetW, photoH / targetH);

    // Decode the image file into a Bitmap sized to fill the View
    bmOptions.inJustDecodeBounds = false;
    bmOptions.inSampleSize = scaleFactor;
    bmOptions.inPurgeable = true;

    Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), bmOptions);
    return bitmap;
  }
Example #23
0
 /**
  * 指定大小的压缩
  *
  * @param path
  * @param limtMax
  * @return
  * @throws java.io.IOException
  */
 private static Bitmap revitionImageSize(String path, int limtMax) throws IOException {
   // 取得图片
   File file = new File(path);
   InputStream temp = new FileInputStream(file);
   BitmapFactory.Options options = new BitmapFactory.Options();
   // 这个参数代表,不为bitmap分配内存空间,只记录一些该图片的信息(例如图片大小),说白了就是为了内存优化
   options.inJustDecodeBounds = true;
   // 通过创建图片的方式,取得options的内容(这里就是利用了java的地址传递来赋值)
   BitmapFactory.decodeStream(temp, null, options);
   // 关闭流
   temp.close();
   // 生成压缩的图片
   int i = 0;
   Bitmap bitmap = null;
   while (true) {
     // 这一步是根据要设置的大小,使宽和高都能满足
     if ((options.outWidth >> i <= limtMax) && (options.outHeight >> i <= limtMax)) {
       // 重新取得流,注意:这里一定要再次加载,不能二次使用之前的流!
       temp = new FileInputStream(file);
       // 这个参数表示 新生成的图片为原始图片的几分之一。
       options.inSampleSize = (int) Math.pow(2.0D, i);
       // 这里之前设置为了true,所以要改为false,否则就创建不出图片
       options.inJustDecodeBounds = false;
       options.inTargetDensity = 240;
       bitmap = BitmapFactory.decodeStream(temp, null, options);
       break;
     }
     i += 1;
   }
   return bitmap;
 }
Example #24
0
  public Bitmap loadImage(String path) throws OutOfMemoryError {
    Bitmap bitsat;

    try {
      BitmapFactory.Options options = new BitmapFactory.Options();
      options.inPreferredConfig = Bitmap.Config.ARGB_8888;
      options.inJustDecodeBounds = true;
      Bitmap b = BitmapFactory.decodeFile(path, options);

      options.inSampleSize = Futils.calculateInSampleSize(options, px, px);

      // Decode bitmap with inSampleSize set
      options.inJustDecodeBounds = false;

      Bitmap bit;
      if (path.startsWith("smb:/")) bit = BitmapFactory.decodeStream(new SmbFileInputStream(path));
      else bit = BitmapFactory.decodeFile(path, options);

      bitsat =
          bit; // decodeFile(path);//.createScaledBitmap(bits,imageViewReference.get().getHeight(),imageViewReference.get().getWidth(),true);
    } catch (Exception e) {
      Drawable img = ContextCompat.getDrawable(mContext, R.drawable.ic_doc_image);
      Bitmap img1 = ((BitmapDrawable) img).getBitmap();
      bitsat = img1;
    }
    return bitsat;
  }
Example #25
0
  /**
   * <图片按比例大小压缩方法(根据路径获取图片并压缩)>
   *
   * @return 压缩后图片路径
   */
  public static String getImageScaleByPath(PicturePropertiesBean propertiesBean, Context context) {
    Bitmap bitmap = null;
    BitmapFactory.Options newOpts = new BitmapFactory.Options();
    // 开始读入图片,此时把options.inJustDecodeBounds 设回true了
    newOpts.inJustDecodeBounds = true;
    bitmap = BitmapFactory.decodeFile(propertiesBean.getSrcPath(), newOpts);
    int width = newOpts.outWidth;
    int height = newOpts.outHeight;
    //        float minHeight = 800f;//设置为主流手机分辨率800*480

    // 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
    int be = 1; // be=1表示不缩放
    if (height > width && width > propertiesBean.getWidth()) {
      // 如果宽度大的话根据宽度固定大小缩放
      be = (int) (newOpts.outWidth / propertiesBean.getWidth());
    } else if (width > height && height > propertiesBean.getHeight()) {
      // 如果高度高的话根据宽度固定大小缩放
      be = (int) (newOpts.outHeight / propertiesBean.getHeight());
    }
    if (be <= 0) be = 1;
    newOpts.inSampleSize = be; // 设置缩放比例
    newOpts.inJustDecodeBounds = false;
    bitmap = BitmapFactory.decodeFile(propertiesBean.getSrcPath(), newOpts);
    return compressImage(bitmap, context, propertiesBean); // 压缩好比例大小后再进行质量压缩
  }
  public static final Bitmap decodeBitmap(String filePath, int targetW, int targetH) {
    // Get the dimensions of the bitmap
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bmOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, bmOptions);
    int photoW = bmOptions.outWidth;
    int photoH = bmOptions.outHeight;

    // Determine how much to scale down the image
    int scaleFactor = Math.min(photoW / targetW, photoH / targetH);

    // Decode the image file into a Bitmap sized to fill the View
    bmOptions.inJustDecodeBounds = false;
    bmOptions.inSampleSize = scaleFactor;
    bmOptions.inPurgeable = true;

    Bitmap src = BitmapFactory.decodeFile(filePath, bmOptions);
    Matrix matrix = getMatrixForImageOrientation(filePath);

    if (src != null) {
      return Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), matrix, true);
    }

    return null;
  }
Example #27
0
  /**
   * Create and returns the Bitmap image from local storage optimized by size
   *
   * @param imageID - filename of the image
   * @param reqSize - maximum side of image returns default image (DEFAULT_IMAGE_NAME) if image
   *     can't be loaded used in ArticleViewAdapter.getView()
   */
  public static Bitmap getBitmapFromStorage(Context context, String imageID, int reqSize) {
    Log.d(TAG, ".getBitmapFromFilePath(), image=" + imageID + ", size=" + reqSize);

    Bitmap result = null;
    // construct full file name
    String fileName = imageID + JPEG_SUFFIX;
    File imageFile = new File(context.getExternalFilesDir(Utils.TYPE_PICTURE), fileName);

    // if image file exists trying to load, optimize and decode
    if (imageFile.exists()) {
      // First decode with inJustDecodeBounds=true to check dimensions
      BitmapFactory.Options bmOptions = new BitmapFactory.Options();
      bmOptions.inJustDecodeBounds = true;
      BitmapFactory.decodeFile(imageFile.getAbsolutePath(), bmOptions);
      // Calculate inSampleSize
      bmOptions.inSampleSize = calculateImageInSampleSize(bmOptions, reqSize, reqSize);

      // Decode bitmap with inSampleSize set from file with given options
      bmOptions.inJustDecodeBounds = false;
      bmOptions.inPurgeable = true;
      result = BitmapFactory.decodeFile(imageFile.getAbsolutePath(), bmOptions);
    }
    // if can't be loaded and decoded, load default image from local storage instead
    if (result == null) {
      Log.d(TAG, ".getBitmapFromFilePath(), cann't decode image:" + imageFile.getAbsolutePath());
      File file = new File(context.getExternalFilesDir(TYPE_PICTURE), DEFAULT_IMAGE_NAME);
      result = BitmapFactory.decodeFile(file.getAbsolutePath());
    }
    return result;
  }
Example #28
0
  private void setPic() {

    /* There isn't enough memory to open up more than a couple camera photos */
    /* So pre-scale the target bitmap into which the file is decoded */

    /* Get the size of the ImageView */
    int targetW = mImageView.getWidth();
    int targetH = mImageView.getHeight();

    /* Get the size of the image */
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bmOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
    int photoW = bmOptions.outWidth;
    int photoH = bmOptions.outHeight;

    /* Figure out which way needs to be reduced less */
    int scaleFactor = 1;
    if ((targetW > 0) || (targetH > 0)) {
      scaleFactor = Math.min(photoW / targetW, photoH / targetH);
    }

    /* Set bitmap options to scale the image decode target */
    bmOptions.inJustDecodeBounds = false;
    bmOptions.inSampleSize = scaleFactor;
    bmOptions.inPurgeable = true;

    /* Decode the JPEG file into a Bitmap */
    Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);

    /* Associate the Bitmap to the ImageView */
    mImageView.setImageBitmap(bitmap);
    mImageView.setVisibility(View.VISIBLE);
  }
  private Bitmap comp(Bitmap image) {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    if (baos.toByteArray().length / 1024 > 1024) {
      // 判断如果图片大于1M,进行压缩避免在生成图片(BitmapFactory.decodeStream)时溢出
      baos.reset(); // 重置baos即清空baos
      image.compress(Bitmap.CompressFormat.JPEG, 50, baos);
      // 这里压缩50%,把压缩后的数据存放到baos中
    }
    ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
    BitmapFactory.Options newOpts = new BitmapFactory.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*500分辨率,所以高和宽我们设置为
    float hh = 800f; // 这里设置高度为800f
    float ww = 500f; // 这里设置宽度为500f
    // 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
    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); // 压缩好比例大小后再进行质量压缩
  }
  @SuppressWarnings("deprecation")
  Bitmap scaleBitmap(Uri imageUri) {
    Display display = getActivity().getWindowManager().getDefaultDisplay();

    int imageViewHeight = display.getHeight();
    int imageViewWidth = display.getWidth();

    BitmapFactory.Options bOptions = new BitmapFactory.Options();
    bOptions.inJustDecodeBounds = true;

    String photoFilePath = imageUri.getPath();

    BitmapFactory.decodeFile(photoFilePath, bOptions);

    int pictureHeight = bOptions.outHeight;
    int pictureWidth = bOptions.outWidth;

    int scaleFactor = Math.min(pictureHeight / imageViewHeight, pictureWidth / imageViewWidth);

    bOptions.inJustDecodeBounds = false;
    bOptions.inSampleSize = scaleFactor;

    Bitmap bitmap = BitmapFactory.decodeFile(photoFilePath, bOptions);
    return bitmap;
  }