Getting size of an image(in kb or mb) selected from gallery programatically

16,625

Solution 1

Change

public String calculateFileSize(Uri filepath)
{
  //String filepathstr=filepath.toString();
  File file = new File(filepath.getPath());

  long fileSizeInKB = fileSizeInBytes / 1024;
  // Convert the KB to MegaBytes (1 MB = 1024 KBytes)
  long fileSizeInMB = fileSizeInKB / 1024;

  String calString=Long.toString(fileSizeInMB);

to

public String calculateFileSize(String filepath)
{
  //String filepathstr=filepath.toString();
  File file = new File(filepath);

  float fileSizeInKB = fileSizeInBytes / 1024;
  // Convert the KB to MegaBytes (1 MB = 1024 KBytes)
  float fileSizeInMB = fileSizeInKB / 1024;

  String calString=Float.toString(fileSizeInMB);

When you use long it will truncate all the digits after . So if your size is of less than 1MB you will get 0.

So instead use float in place of long

Solution 2

Just try this one and it will work for you

private void getImageSize(Uri choosen) throws IOException {
        Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), choosen);

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        byte[] imageInByte = stream.toByteArray();
        long lengthbmp = imageInByte.length;

        Toast.makeText(getApplicationContext(),Long.toString(lengthbmp),Toast.LENGTH_SHORT).show();

    }

And on result

 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch(requestCode) {
            case SELECT_PHOTO:
                if(resultCode == RESULT_OK){
                    Uri selectedImage = data.getData();

                    if(selectedImage !=null){

                        img.setImageURI(selectedImage);

                        try {
                            getImageSize(choosenPhoto);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        //txt1.setText("Initial size: " +getImageSize(choosenPhoto)+ " Kb");
                    }
                }
        }
    }

Solution 3

use uri.getLastPathSegment() instead of uri.getPath()

public static float getImageSize(Uri uri) {

    File file = new File(uri.getLastPathSegment());
    return file.length(); // returns size in bytes
}

IMPORTANT

The above code will only work for images that you pick from gallery; and doesn't work for those from file manager as it won't recognize the scheme of the URI

The below method will work in either case

public static float getImageSize(Context context, Uri uri) {
    Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
    if (cursor != null) {
        int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
        cursor.moveToFirst();
        float imageSize = cursor.getLong(sizeIndex);
        cursor.close();
        return imageSize; // returns size in bytes
    }
    return 0;
}

To change from bytes into Kbytes >>> /1024f

To change from bytes into Mbytes >>> /(1024f * 1024f)

Solution 4

It is a method for calculating image size chosen from the gallery. you can pass the Uri which you get from intent in onActivityResult :

public static double getImageSizeFromUriInMegaByte(Context context, Uri uri) {
    String scheme = uri.getScheme();
    double dataSize = 0;
    if (scheme.equals(ContentResolver.SCHEME_CONTENT)) {
        try {
            InputStream fileInputStream = context.getContentResolver().openInputStream(uri);
            if (fileInputStream != null) {
                dataSize = fileInputStream.available();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else if (scheme.equals(ContentResolver.SCHEME_FILE)) {
        String path = uri.getPath();
        File file = null;
        try {
            file = new File(path);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (file != null) {
            dataSize = file.length();
        }
    }
    return dataSize / (1024 * 1024);
}
Share:
16,625
kgandroid
Author by

kgandroid

This is Kaustav Ghosh.I am a mobile app developer specially native android.Learning hybrid app frameworks.I always like to explore new technologies and learn new languages and frameworks.I love to take challenges. My linkedin profile. #SOreadytohelp

Updated on June 04, 2022

Comments

  • kgandroid
    kgandroid about 2 years

    I am selecting an image from gallery.I want to determine the size of the image programatically in kb or mb. This is what I have written:

    public String calculateFileSize(Uri filepath)
    {
        //String filepathstr=filepath.toString();
        File file = new File(filepath.getPath());
    
        // Get length of file in bytes
        long fileSizeInBytes = file.length();
        // Convert the bytes to Kilobytes (1 KB = 1024 Bytes)
        long fileSizeInKB = fileSizeInBytes / 1024;
        // Convert the KB to MegaBytes (1 MB = 1024 KBytes)
        long fileSizeInMB = fileSizeInKB / 1024;
    
        String calString=Long.toString(fileSizeInMB);
        return calString;
    }
    

    The uri of the image when selected from gallery is coming perfectly.But the value of fileSizeInBytes is zero.I am calling this method on onActivityResult ,after selecting the image from gallery.I saw a few same questions asked here before.But none worked for me.Any solution?