从库中的选定图像中获取图像的确切文件大小

时间:2017-03-07 03:01:39

标签: android image

这是我的文件选择器代码

 private void showFileChooser() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}

然后onActivityResult()

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

        filePath = data.getData();
        try {
            bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), filePath);

            System.out.println(bitmap.getByteCount());

            int w = bitmap.getWidth();
            int h = bitmap.getHeight();



            if (w!= 512 || h!= 512)
            {
                txvLogoError.setText("Invalid image dimensions. Please choose another.");
            }
            else
            {
                txvLogoError.setText("");
                imbAppLogo.setPadding(10,10,10,10);
                imbAppLogo.setImageBitmap(bitmap);
            }


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

我的问题是,如何才能获得所选图像的确切文件大小?我尝试了File.length()但结果是0。

2 个答案:

答案 0 :(得分:10)

试试这个。

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        int dataSize=0;
        if (requestCode == 2 && resultCode == RESULT_OK)
        {
            Uri uri  = data.getData();
            String scheme = uri.getScheme();
            System.out.println("Scheme type " + scheme);
            if(scheme.equals(ContentResolver.SCHEME_CONTENT))
            {
                try {
                    InputStream fileInputStream=getApplicationContext().getContentResolver().openInputStream(uri);
                    dataSize = fileInputStream.available();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("File size in bytes"+dataSize);

            }
            else if(scheme.equals(ContentResolver.SCHEME_FILE))
            {
                String path = uri.getPath();
                try {
                    f = new File(path);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("File size in bytes"+f.length());
            }

        }
    }

答案 1 :(得分:1)

尝试以下方法,

File f = new File(filePath.getPath());
long size = f.length();

否则你可以尝试

Cursor returnCursor = getContentResolver().query(filePath, null, null, null, null);

int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);