如何以 kb 为单位获取位图的大小

How to get the size of bitmap in kb

我正在尝试在 firebase 存储中上传图像,我希望图像不应大于 50 kb 我正在尝试获取位图的大小,以便我可以知道位图的大小是否大于50kb 图片不会显示在图库中 我已经尝试了许多人建议的代码,但其中 none 对我有用。请帮我解决这个问题。这是我的代码:

@Override
protected void onActivityResult( int requestCode , int resultCode , @Nullable Intent data )

  {
    super.onActivityResult (requestCode , resultCode , data);
    if(requestCode == ChooseImage && resultCode == RESULT_OK && data != null && data.getData() != null){

     userProfileImage = data.getData ();

    try {

      Bitmap bitmap=MediaStore.Images.Media.getBitmap (getContentResolver ( ) , userProfileImage);       

            if (bitmap.getHeight () * bitmap.getRowBytes () < 50000)
                    profile_photo.setImageBitmap (bitmap);
                    btn.setOnClickListener (new View.OnClickListener ( ) {
                        @Override
                        public void onClick( View v ) {
                            uploaImage ();
                        }
                    });


        } catch (IOException e) {
            e.printStackTrace ( );
            Toast.makeText (this , e.getMessage () , Toast.LENGTH_SHORT).show ( );
        }
    }
}

试试这个代码:

@Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        if (requestCode == ChooseImage && resultCode == RESULT_OK && data != null && data.getData() != null) {
            userProfileImage = data.getData();
            try {

                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), userProfileImage);
                if (bitmap.getHeight() * bitmap.getRowBytes() < 50000)
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                    byte[] imageInByte = stream.toByteArray();
                    long bitmap_size = imageInByte.length / 1024; 
                    profile_photo.setImageBitmap(bitmap);

                    btn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            uploaImage();
                        }
                    });


            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    }

长变量 bitmap_size 将为您提供以 KB 为单位的图像大小

您可以使用此代码获取以 KB 为单位的大小:

ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); 
byte[] imageInByte = stream.toByteArray(); 
long sizeInKB = imageInByte.length / 1024;    //Size in KB

谢谢。