I want to display this image and upload it to a server.
I’m using the camera app to take a photo and returning the file path of the photo to an activity. I run into an Out of Memory error on some phones because I have a constant image size that I try and import between devices.
How can I pull in the largest image size possible to upload to the server while still working within the memory constraints of the phone?
Code Follows:
request to load Aync
GetBitmapTask GBT = new GetBitmapTask(dataType, path, 1920, 1920, loader);
GBT.addAsyncTaskListener(new AsyncTaskDone()
{
@Override
public void loaded(Object resp)
{
crop.setImageBitmap((Bitmap)resp);
crop.setScaleType(ScaleType.MATRIX);
}
@Override
public void error() {
}
});
GBT.execute();
The Async Task that throws the OOM error
public class GetBitmapTask extends AsyncTask<Void, Integer, Bitmap>
{
...
@Override
public Bitmap doInBackground(Void... params)
{
Bitmap r = null;
if (_dataType.equals("Unkown"))
{
Logger.e(getClass().getName(), "Error: Unkown File Type");
return null;
}
else if (_dataType.equals("File"))
{
Options options = new Options();
options.inJustDecodeBounds = true;
//Logger.i(getClass().getSimpleName(), _path.substring(7));
BitmapFactory.decodeFile(_path.substring(7), options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
Logger.i(getClass().getSimpleName(),
"height: " + options.outHeight +
"\nwidth: " + options.outWidth +
"\nmimetype: " + options.outMimeType +
"\nsample size: " + options.inSampleSize);
options.inJustDecodeBounds = false;
r = BitmapFactory.decodeFile(_path.substring(7), options);
}
else if (_dataType.equals("Http"))
{
r = _loader.downloadBitmap(_path, reqHeight);
Logger.i(getClass().getSimpleName(), "height: " + r.getHeight() +
"\nwidth: " + r.getWidth());
}
return r;
}
public static int calculateInSampleSize( Options options, int reqWidth, int reqHeight)
{
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
while (height / inSampleSize > reqHeight || width / inSampleSize > reqWidth)
{
if (height > width)
{
inSampleSize = height / reqHeight;
if (((double)height % (double)reqHeight) != 0)
{
inSampleSize++;
}
}
else
{
inSampleSize = width / reqWidth;
if (((double)width % (double)reqWidth) != 0)
{
inSampleSize++;
}
}
}
return inSampleSize;
}
}
You can give the camera the uri pointing to file you want to save the image into:
You can then upload that file to your server, so you have the full bitmap size. On the other hand, there is no need (and on many devices no way) to decode and show bitmap 1920×1920 (or similar) in UI, it’s just too big.
Hope this helps.