Reputation: 11216
I successfully wrote an app, based on this blog post, but simpler, which streams an image over HTTP, using a POST request.
What I can't figure out (after searching the web and crawling inside android SDK docs) is, how do I get the size of the image before I share it?
There is only a possibility to open an input stream that I see in the exampkle and anywhere else:
ContentResolver cr = getContentResolver();
InputStream is = cr.openInputStream(uri);
The given blog post example uses getBytesFromFile(is)
, so one could get the size there, but this is not a solution. Some images are huge, while android apps are limited in heap space. I want my app to work for all thinkable sizes of images (not a problem when sharing over Wifi).
Therefor, the only option for me is to "forward" the input stream to some HTTP output stream, which I do and which works. But this approach don't give me the image size before sending it.
Upvotes: 13
Views: 9209
Reputation: 435
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 9991) {
if (data == null) {
//no data present
return;
}
ContentResolver cr = getContentResolver();
InputStream is = null;
File file = new File(fileUri.getPath());
try {
is = cr.openInputStream(fileUri);
cr.getType(fileUri);
int size = is.available();
Log.d(TAG, "Size 151: " + getFileSize(size));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Here's how I fixed my issue similar to this, this will work for Android API below KITKAT.
private static final DecimalFormat format = new DecimalFormat("#.##");
private static final long MiB = 1024 * 1024;
private static final long KiB = 1024;
public String getFileSize(long file) {
final double length = Double.parseDouble(String.valueOf(file));
if (length > MiB) {
return format.format(length / MiB) + " MiB";
}
if (length > KiB) {
return format.format(length / KiB) + " KiB";
}
return format.format(length) + " B";
}
Upvotes: 5
Reputation: 3908
Just ask the InputStream for the number available bytes to get the file size.
ContentResolver cr = getContentResolver();
InputStream is = cr.openInputStream(uri);
int size = is.available();
This worked quite reliable once. Don't know if that still holds true as the result is not guaranteed to account for all bytes in the file.
Upvotes: -2
Reputation: 988
You can also check it this way:
Uri fileUri = resultData.getData();
Cursor cursor = getActivity().getContentResolver().query(fileUri,
null, null, null, null);
cursor.moveToFirst();
long size = cursor.getLong(cursor.getColumnIndex(OpenableColumns.SIZE));
cursor.close();
Source: https://developer.android.com/training/secure-file-sharing/retrieve-info.html
Upvotes: 27