I'm trying to take a picture and add an overlay on top of it. Here is my code (only the callback) :
private PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(final byte[] data, Camera camera) {
if(!dirFile.exists()){
dirFile.mkdirs();
}
try {
String name = new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date()) + ".jpg";
picturePath = new File(dirFile, name);
new AsyncTask<Void, Void, Void>(){
FileOutputStream fos = new FileOutputStream(picturePath);
Bitmap photo;
#Override
protected Void doInBackground(Void... params) {
photo = BitmapFactory.decodeByteArray(data, 0, data.length).copy(Config.ARGB_8888, true);
Bitmap cadre = BitmapFactory.decodeResource(getResources(), R.drawable.cadre16001200);
Canvas canvas = new Canvas(photo);
canvas.drawBitmap(cadre, new Matrix(), null);
cadre.recycle();
photo.compress(CompressFormat.JPEG, 100, fos);
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
geotag(picturePath.toString());
return null;
}
protected void onPostExecute(Void result) {
dialog.dismiss();
mCamera.startPreview();
//Affiche la nouvelle photo
picture.setImageBitmap(photo);
};
}.execute();
} catch (FileNotFoundException e) {
Log.d("PhotoActivity", "File not found: " + e.getMessage());
}
}
};
I get the following error on my Samsung Galaxy S3 (android 4.1.2) , with an OutOfMemoryException
07-04 10:01:24.076: E/dalvikvm-heap(2980): Out of memory on a 7680016-byte allocation.
Weird thing is that it works perfectly on the Samsung Gio (android 2.2.1) with the same resolution of 1600x1200.
I googled a lot, and I can't use the main solution of downsizing the picture. It is a memory issue, but I don't know how I can reduce the memory usage.
EDIT : I found this, seems it was the real matter : https://stackoverflow.com/a/12377158/1343969
you should decode the bitmap before proccessing it to the UI, here's a code example
private Bitmap decodeFile(File f){
try {
//decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream stream1=new FileInputStream(f);
BitmapFactory.decodeStream(stream1,null,o);
stream1.close();
//Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE=70;
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
while(true){
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}
//decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
FileInputStream stream2=new FileInputStream(f);
Bitmap bitmap=BitmapFactory.decodeStream(stream2, null, o2);
stream2.close();
return bitmap;
} catch (FileNotFoundException e) {
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
You should simply call the empty constructor of Canvas and draw the photo on it. This would remove the copy() call and reduce the memory usage.
photo = BitmapFactory.decodeByteArray(data, 0, data.length);
Bitmap cadre = BitmapFactory.decodeResource(getResources(), R.drawable.cadre16001200);
Canvas canvas = new Canvas();
canvas.drawBitmap(photo, 0, 0, null);
canvas.drawBitmap(cadre, new Matrix(), null);
cadre.recycle();
photo.compress(CompressFormat.JPEG, 100, fos);
Related
I'm trying to set wallpaper from file path. However it takes more than 10 seconds and causes my app to freeze.
Here's the code I'm using:
public void SET_WALLPAPER_FROM_FILE_PATH (String file_path)
{
Bitmap image_bitmap;
File image_file;
FileInputStream fis;
try {
WallpaperManager wallpaper_manager = WallpaperManager.getInstance(m_context);
image_file = new File(file_path);
fis = new FileInputStream(image_file);
image_bitmap = BitmapFactory.decodeStream(fis);
wallpaper_manager.setBitmap(image_bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
I have tried to use:
wallpaper_manager.setStream(fis)
instead of:
wallpaper_manager.setBitmap(image_bitmap);
as suggested in this answer but couldn't load the wallpaper.
Can anyone guide me?
Thanks
Try to use AsyncTask,
in doInBackground method write something like this
public static Bitmap decodeFile(File f,int WIDTH,int HIGHT){
try {
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//The new size we want to scale to
final int REQUIRED_WIDTH=WIDTH;
final int REQUIRED_HIGHT=HIGHT;
//Find the correct scale value. It should be the power of 2.
int scale=1;
while(o.outWidth/scale/2>=REQUIRED_WIDTH && o.outHeight/scale/2>=REQUIRED_HIGHT)
scale*=2;
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
}
catch (FileNotFoundException e) {}
return null;
}
Objective of the program: the user is able to place one picture on the top of camera preview and move it freely (image is big 1920x1080 pixels) and can store this two layers (picture and camera preview) pressing the photo button. So far he is only able to save one picture of this kind because when he takes the second one the out of memory error problem appears.
Solution It seems that the problem can be solved if you use recycle bitmap function when you dont need to use bitmaps anymore. Or you can resize them (didn't want to)... Are these good ideas?
Code:
private PictureCallback mPicture = new PictureCallback()
{
#Override
public void onPictureTaken(byte[] data, Camera camera)
{
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
mPreview.setDrawingCacheEnabled(true);
mPreview.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_AUTO);
Bitmap bitmap = mPreview.getDrawingCache();
bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
combination = overlay(bmp, bitmap);
if(pictureFile == null)
{
return;
}
try
{
FileOutputStream fos = new FileOutputStream(pictureFile);
combination.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"+ mediaStorageDir)));
}
catch(FileNotFoundException e)
{
Log.d(TAG, "File not found: "+e.getMessage());
}
catch(IOException e)
{
Log.d(TAG, "Error accessing file: "+e.getMessage());
}
}
};
public static Bitmap overlay(Bitmap bmp1, Bitmap bmp2)
{
Bitmap bmOverlay = Bitmap.createBitmap(bmp1.getWidth(), bmp1.getHeight(),bmp1.getConfig());
Canvas canvas = new Canvas(bmOverlay);
canvas.drawBitmap(bmp1, new Matrix(), null);
canvas.drawBitmap(bmp2, null, new Rect(0,0,bmp1.getWidth(), bmp1.getHeight()), null);
return bmOverlay;
}
private static File getOutputMediaFile(int type)
{
File mediaFile = null;
if(isSdPresent() == false)
{
Log.d(TAG, "There is no Sd card. Cannot use the camera");
}
else
{
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "World Cup Camera");
if(!mediaStorageDir.exists())
{
if(!mediaStorageDir.mkdirs())
{
Log.d("WorldCupApp", "failed to create directory");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
if (type == MEDIA_TYPE_IMAGE)
{
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg");
}
else
{
return null;
}
}
return mediaFile;
}
I heard about this code should I use?
private Bitmap decodeFile(File f)
{
try
{
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//The new size we want to scale to
final int REQUIRED_SIZE=70;
//Find the correct scale value. It should be the power of 2.
int scale=1;
while(o.outWidth/scale/2>=REQUIRED_SIZE && o.outHeight/scale/2>=REQUIRED_SIZE)
scale*=2;
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
}
catch (FileNotFoundException e) {}
return null;
}
You can use android:largeHeap="true" inside the application tag on AndroidManifest when you're having outofmemory errors.
I am working on a code sample where I have to choose an image from gallery the code is working but after selection of image from gallery I get OutOfMemoryError in my OnActivityResult
I am able to get small images but large images are creating problem.
Here is my code:
try{
Uri selectedImageUri = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImageUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
bitmap = BitmapFactory.decodeFile(filePath);
_profileImage.setImageBitmap(bitmap);
_profileImage.setScaleType(ScaleType.FIT_XY);
Constant._addPhotoBitmap=bitmap;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Bitmap resizedbitmap = Bitmap.createScaledBitmap(bitmap, 200, 200, true);
resizedbitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte [] _byteArray = baos.toByteArray();
String base64 = Base64.encodeToString(_byteArray,Base64.DEFAULT);
Constant._addPhotoBase64 = base64;
}catch (OutOfMemoryError e) {
e.printStackTrace();
Constant.showAlertDialog(Constant.errorTitle,
"Image size is too large.Please upload small image.",
DriverProfileScreen.this, false);
} catch (Exception e) {
e.printStackTrace();
}
You are deirectly decoding the file based on its uri path..thats why it is throwing exception..before loading image set some options..this will reduce the memory for the image loading..Use this method for loading image whatever size you want..
/**
* returns the thumbnail image bitmap from the given url
*
* #param path
* #param thumbnailSize
* #return
*/
private Bitmap getThumbnailBitmap(final String path, final int thumbnailSize) {
Bitmap bitmap;
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, bounds);
if ((bounds.outWidth == -1) || (bounds.outHeight == -1)) {
bitmap = null;
}
int originalSize = (bounds.outHeight > bounds.outWidth) ? bounds.outHeight
: bounds.outWidth;
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = originalSize / thumbnailSize;
bitmap = BitmapFactory.decodeFile(path, opts);
return bitmap;
}
In Android Developer document there is Topic called
Displaying Bitmaps Efficiently
So please go through it.
http://developer.android.com/training/displaying-bitmaps/index.html
Hope this will help you.
Generally android device heap size is only 16MB (varies from device/OS see post Heap Sizes), if you are loading the images and it crosses the size of 16MB , it will throw out of memory exception, instead of using the Bitmap for , loading images from SD card or from resources or even from network try to using getImageUri , loading bitmap require more memory , or you can set bitmap to null if your work done with that bitmap.
So,You need to downscale you image using below code:
public static Bitmap decodeFile(File f,int WIDTH,int HIGHT){
try {
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//The new size we want to scale to
final int REQUIRED_WIDTH=WIDTH;
final int REQUIRED_HIGHT=HIGHT;
//Find the correct scale value. It should be the power of 2.
int scale=1;
while(o.outWidth/scale/2>=REQUIRED_WIDTH && o.outHeight/scale/2>=REQUIRED_HIGHT)
scale*=2;
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}
Scale the bitmap first , then load it. It will solve the problem.
You can use the following method to do that.
private Bitmap getScaledBitmap(Uri uri){
Bitmap thumb = null ;
try {
ContentResolver cr = getContentResolver();
InputStream in = cr.openInputStream(uri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize=8;
thumb = BitmapFactory.decodeStream(in,null,options);
} catch (FileNotFoundException e) {
Toast.makeText(PhotoTake.this , "File not found" , Toast.LENGTH_SHORT).show();
}
return thumb ;
}
Hope it helps.
try this code:
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.ActivityManager;
import android.content.ComponentCallbacks;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v4.util.LruCache;
import android.widget.ImageView;
public class UserImageLoaderWithCache implements ComponentCallbacks {
private KCLruCache cache;
public UserImageLoaderWithCache(Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
int memoryClass = am.getMemoryClass() * 1024 * 1024;
cache = new KCLruCache(memoryClass);
}
public void display(String url, ImageView imageview, int defaultresource) {
imageview.setImageResource(defaultresource);
Bitmap image = cache.get(url);
if (image != null) {
imageview.setImageBitmap(image);
}
else {
new SetImageTask(imageview).execute(url);
}
}
private class KCLruCache extends LruCache<String, Bitmap> {
public KCLruCache(int maxSize) {
super(maxSize);
}
}
private class SetImageTask extends AsyncTask<String, Void, Integer> {
private ImageView imageview;
private Bitmap bmp;
public SetImageTask(ImageView imageview) {
this.imageview = imageview;
}
#Override
protected Integer doInBackground(String... params) {
String url = params[0];
try {
bmp = getBitmapFromURL(url);
if (bmp != null) {
cache.put(url, bmp);
} else {
return 0;
}
} catch (Exception e) {
e.printStackTrace();
return 0;
} catch (OutOfMemoryError o) {
o.printStackTrace();
return 0;
}
return 1;
}
#Override
protected void onPostExecute(Integer result) {
if (result == 1) {
imageview.setImageBitmap(bmp);
}
super.onPostExecute(result);
}
private Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (Exception e) {
e.printStackTrace();
return null;
}catch (OutOfMemoryError o) {
o.printStackTrace();
return null;
}
}
}
public void onLowMemory() {
}
/*public void onTrimMemory(int level) {
if (level >= TRIM_MEMORY_MODERATE) {
cache.evictAll();
}
else if (level >= TRIM_MEMORY_BACKGROUND) {
cache.trimToSize(cache.size() / 2);
}
}*/
public void onConfigurationChanged(Configuration arg0) {
// TODO Auto-generated method stub
}
}
I have used below code and used bitmap to store resized Image in local storage and It worked like charm
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap b = BitmapFactory.decodeFile(path, options);
here path is image Uri path in String
I am trying to download images from URL. The image type is PNG and the resolution is 400x400 pixels.
Here is the download code snippet.
Bitmap bitmap=null;
URL imageUrl = new URL(url);
conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream ins=conn.getInputStream();
os = new FileOutputStream(f);
Utilities.getUtilities().copyStream(ins, os);
os.flush();
Log.i(TAG_NAME, "file size : "+ f.length());
Log.i(TAG_NAME, "file exists in cache? " + f.exists());
bitmap = decodeFile(f);
return bitmap;
Here is the file writer.
public void copyStream(InputStream is, OutputStream os) {
final int buffer_size=1024;
try
{
byte[] bytes=new byte[buffer_size];
for(;;)
{
int count=is.read(bytes, 0, buffer_size);
if(count==-1)
break;
os.write(bytes, 0, count);
}
}
catch(Exception ex){
ex.printStackTrace();
}
}
And the decode method
private Bitmap decodeFile(File f){
//decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
try {
BitmapFactory.decodeStream(new FileInputStream(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
final int REQUIRED_SIZE = 400; //for testing, it is set to b a constant
System.out.println("REQUIRED_SIZE >>> " + REQUIRED_SIZE);
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
while(true){
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}
//decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
//o2.inJustDecodeBounds = true;
o2.inPreferredConfig = Bitmap.Config.ARGB_8888;
o2.inSampleSize=scale; //scale is set off since android:src automatically scales the image to fit the screen
try {
return BitmapFactory.decodeStream(new FileInputStream(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
I can see that the file exists in the device. However, the decode stream is failing. I spent hours searching on the internet; tried almost everything, no success and almost my heads rolling.
Decode streams is causing the following error.
SkImageDecoder::Factory returned null
Do you find anything missing here?
EDIT:
Issue is now solved. The server was expecting cookie details which I failed to attach. Spent almost a day, beating around the bushes :-)
Thanks all for the valuable comments!
IMO, you may want to re-evaluate merits of httpurlconn vs native httpclient implementation. Android/google go for httpurlconn but, many opt to take greater control of low level details surrounding net protocol.
Here is sample async httpclient that wraps in bitmap handler. You can easily extend the sample method=processBitmapEntity() with your rules affecting bmp size.
Sample getbitmap url:
public int getBitmap(String mediaurl, int ctr){
Handler handler = new Handler() {
public void handleMessage(Message message) {
switch (message.what) {
case HttpConnection.DID_START: {
Log.d(TAG, "Starting connection...");
break;
}
case HttpConnection.DID_SUCCEED: {
//message obj is type bitmap
Log.d(TAG, "OK bmpARRAY " +message.arg1);
Bitmap response = (Bitmap) message.obj;
break;
}
case HttpConnection.DID_ERROR: {
Exception e = (Exception) message.obj;
e.printStackTrace();
Log.d(TAG, "Connection failed.");
break;
}
}
}
};
new HttpConnection(handler, PreferenceManager.getDefaultSharedPreferences(this), ctr).bitmap(mediaurl);
return -1;
And the bitmap handler in HttpConnection class that is part of the link sample above:
private void processBitmapEntity(HttpEntity entity) throws IOException {
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
Bitmap bm = BitmapFactory.decodeStream(bufHttpEntity.getContent());
handler.sendMessage(Message.obtain(handler, DID_SUCCEED, bm));
}
And a git project
im using a custom method to decode bitmap and set it to imageview as background. For now it's working fine, but in some devices sometimes it's crashing due to out ot memory error. Any idea how can I optime that code and make it better? Here is what I am using :
class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
private String data = null;
public BitmapWorkerTask(ImageView imageView) {
// Use a WeakReference to ensure the ImageView can be garbage collected
imageViewReference = new WeakReference<ImageView>(imageView);
}
// Decode image in background.
#Override
protected Bitmap doInBackground(String... params) {
data = params[0];
if(data != null){
File bufferFile = new File(data);
Log.e("","data : "+data);
FileInputStream fis = null;
try {
fis = new FileInputStream(bufferFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Cipher cipher = null;
try {
cipher = Cipher.getInstance("AES/CBC/NoPadding");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}
int userId = RPCCommunicator.getUserId(Store.this);
String secretSalt = RPCCommunicator.getSecretKey(userId);
String iv = RPCCommunicator.getIv(secretSalt);
SecretKeySpec keySpec = new SecretKeySpec(secretSalt.getBytes(), "AES");
IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes());
try {
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
}
CipherInputStream cis = new CipherInputStream(fis, cipher);
BitmapFactory.Options o2 = new BitmapFactory.Options();
//o2.inSampleSize=2;
o2.inTempStorage = new byte[4*1024];
int width = (int) RPCCommunicator.getPlaceHolderWidth(Store.this, 45);
int height = (int) RPCCommunicator.getPlaceHolderHeight(Store.this, 25);
Rect rect = new Rect();
rect.inset(width, height);
Bitmap finall = BitmapFactory.decodeStream(cis,rect,o2);
if(finall != null){
Bitmap bmp = Bitmap.createScaledBitmap(finall, width, height, true);
return bmp;
} else {
return null;
}
}
return null;
}
// Once complete, see if ImageView is still around and set bitmap.
#Override
protected void onPostExecute(Bitmap bitmap) {
if (imageViewReference != null) {
final ImageView imageView = imageViewReference.get();
if(bitmap != null){
if (imageView != null) {
Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fadein);
imageView.startAnimation(animation);
imageView.setImageBitmap(bitmap);
}
} else {
int width = (int) RPCCommunicator.getPlaceHolderWidth(Store.this, 45);
int height = (int) RPCCommunicator.getPlaceHolderHeight(Store.this, 25);
RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams(width, height);
param.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
param.rightMargin = 15;
imageView.setBackgroundResource(R.drawable.placeholder);
imageView.setLayoutParams(param);
}
}
}
}
Any ideas / suggestions / helps are really appreciated!
try this code
public static Bitmap decodeFile(File f,int WIDTH,int HIGHT){
try {
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//The new size we want to scale to
final int REQUIRED_WIDTH=WIDTH;
final int REQUIRED_HIGHT=HIGHT;
//Find the correct scale value. It should be the power of 2.
int scale=1;
while(o.outWidth/scale/2>=REQUIRED_WIDTH && o.outHeight/scale/2>=REQUIRED_HIGHT)
scale*=2;
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
}
catch (FileNotFoundException e) {}
return null;
}
this will scale bitmap as you pass width and height..
Use bitmap.recycle() after using your bitmap and before allocating it another value. You can also scale your bitmap down before actually using it. Here's a link: https://stackoverflow.com/a/13226982/1117338
Also one advice: please search well before posting questions. This is an old problem already solved by many.