Android Bitmap无法扩展

时间:2013-11-04 11:04:16

标签: android bitmap scale

我尝试缩放图片并且最初效果很好,但是当缩小时它似乎不起作用。过了一会儿它停止缩小。在质量为0时,我无法获得小于630的字节数。我意识到这是一个糟糕的图片,但我想要将其缩小很多而且根本不起作用。任何想法都将不胜感激。

    ByteArrayOutputStream out;
    Bitmap bitmap = BitmapFactory.decodeStream(in);
    int width = bitmap.getWidth(); //3920
    int height = bitmap.getHeight(); //2204

    float scale = 0.0034; //usually calculated in runtime but set for simplicity now.

    // Resize the bitmap
    Matrix matrix = new Matrix();
    matrix.postScale(scale, scale);

    // Recreate the new bitmap
    Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);

    out = new ByteArrayOutputStream();
    resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 0, out);

    return out.toByteArray();

2 个答案:

答案 0 :(得分:0)

您可以使用矩形重新缩放位图

Rect srcrect = new Rect(0,0,yourbitmap.getWidth(),yourbitmap.getHeight());
Rect destrect = new Rect(startindexxright,startindexyright,startindexxleft,startindexyleft);
canvas.drawBitmap(yourbitmap, srcrect,destrect, null);

srcrect是一个矩形,您必须输入位图的详细信息,而destrect是设备显示区域(您要在其中显示图像的部分)。

答案 1 :(得分:0)

检查BitmapFactory.Options.InSampleSize

此代码减少了存储在文件中的位图,但应该很容易使代码适应内存中的位图

 public static Bitmap getReducedBitmap(Context context, String path) {    
    File bitmapFile = new File(path);

    Uri uri = Uri.fromFile(bitmapFile);
    InputStream in = null;

    ContentResolver contentResolver = context.getContentResolver();

    try {
      in = contentResolver.openInputStream(uri);

      // Decode image size
      BitmapFactory.Options options = new BitmapFactory.Options();
      options.inJustDecodeBounds = true;
      BitmapFactory.decodeStream(in, null, options);
      in.close();

      //scale works better with powers of 2
      int scale = 1;
      while ((options.outWidth * options.outHeight) * (1 / Math.pow(scale, 2)) > WSConfig.PICTURE_MAX_PIXELS) {
        scale++;
      }

      Bitmap reducedBitmap = null;
      in = contentResolver.openInputStream(uri);
      if (scale > 1) {
        // scale to max possible inSampleSize that still yields an image
        // larger than target
        options = new BitmapFactory.Options();
        options.inSampleSize = scale;
        reducedBitmap = BitmapFactory.decodeStream(in, null, options);    
      } else {
        reducedBitmap = BitmapFactory.decodeStream(in);
      }
      in.close();

      return reducedBitmap;
    } catch (IOException e) {
      Log.e("UTILS", e.getMessage(), e);
      return null;
    }
  }

我的MAX_PICTURE_PICTURES确定最大分辨率