Bitmap.createScaledBitmap无法调整图像大小

时间:2017-12-27 06:34:44

标签: android bitmap imageview

我正在尝试实现一个代码,其中用户将添加图像,如果大小更大,则图像的大小应小于3MB,然后它将自动调整大小。我知道这个问题反复询问,但我的代码工作不正常。

以下是我的代码

  Uri selectedImage = data.getData();
            String[] filePath = {MediaStore.Images.Media.DATA};
            Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
            c.moveToFirst();
            int columnIndex = c.getColumnIndex(filePath[0]);
            String picturePath = c.getString(columnIndex);
            c.close();
            bitmap2 = (BitmapFactory.decodeFile(picturePath));
            Log.e("path of image 4", picturePath + "");
            String str = String.valueOf(bitmap2.getRowBytes() * bitmap2.getHeight());
            Log.e("lengh of bitmap.......", str);
          //  Log.e("lengh of bitmap", String.valueOf(bitmap2.getAllocationByteCount()));

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap2.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            byte[] bitmapdata = bos.toByteArray();

            Bitmap resized = Bitmap.createScaledBitmap(bitmap2, 200, 300, true);

            imageView2.setImageBitmap(resized);
            setImage("image2");

I have tried this link

And this

1 个答案:

答案 0 :(得分:3)

根据我的理解,您可以执行此操作,也可以按照This Link

进行操作
Bitmap yourBitmap;
Bitmap resized = Bitmap.createScaledBitmap(yourBitmap, newWidth, newHeight, true);

或:

resized = Bitmap.createScaledBitmap(yourBitmap,(int)(yourBitmap.getWidth()*0.8), (int)(yourBitmap.getHeight()*0.8), true);

您也可以使用此方法

public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {

int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// create a matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);

return resizedBitmap;

 }