Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the exact File Size of an Image from the selected image in gallery

Tags:

android

image

This is my code for file chooser

 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);
}

then 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();
        }
    }
}

my question is, how can I get the exact file size of the image selected? I tried File.length() but the result is 0.

like image 490
Paul John Pulumbarit Avatar asked Nov 30 '22 15:11

Paul John Pulumbarit


1 Answers

Try this .

@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());
            }

        }
    }
like image 199
Ayush Bansal Avatar answered Dec 04 '22 12:12

Ayush Bansal