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?
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