java.lang.OutOfMemoryError while display the images in gallery - android

When i was loading images form sd card i got the exception
java.lang.OutOfMemoryError at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
Here is my code:
public class Images extends Activity implements OnItemLongClickListener {
private Uri[] mUrls;
String[] mFiles = null;
ImageView selectImage;
Gallery g;
static final String MEDIA_PATH = new String("/mnt/sdcard/DCIM/Camera/");
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
selectImage = (ImageView) findViewById(R.id.image);
g = (Gallery) findViewById(R.id.gallery);
File images = new File(MEDIA_PATH);
Log.i("files", images.getAbsolutePath());
File[] imagelist = images.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return ((name.endsWith(".jpg")) || (name.endsWith(".png")));
}
});
Log.i("files", imagelist.toString());
String[] mFiles = null;
mFiles = new String[imagelist.length];
for (int i = 0; i < imagelist.length; i++) {
mFiles[i] = imagelist[i].getAbsolutePath();
}
System.out.println(mFiles.length);
mUrls = new Uri[mFiles.length];
System.out.println(mUrls.length);
for (int i = 0; i < mFiles.length; i++) {
mUrls[i] = Uri.parse(mFiles[i]);
}
g.setAdapter(new ImageAdapter(this));
// g.setOnItemSelectedListener(this);
g.setOnItemLongClickListener(this);
}
public class ImageAdapter extends BaseAdapter {
// int mGalleryItemBackground;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mUrls.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
Log.i("ok5", "ok");
ImageView i = new ImageView(mContext);
i.setImageURI(mUrls[position]);
Log.i("ok", "ok");
i.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
i.setLayoutParams(new Gallery.LayoutParams(100, 100));
return i;
}
private Context mContext;
}
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
selectImage.setImageURI(mUrls[arg2]);
System.out.println("path: "+mUrls[arg2]);
Uri f = mUrls[arg2];
File f1 = new File(f.toString());
System.out.println("f1: "+f1);
return false;
}

While you load large bitmap files, BitmapFactory class provides several decoding methods (decodeByteArray(), decodeFile(), decodeResource(), etc.).
STEP 1
Setting the inJustDecodeBounds property to true while decoding avoids memory allocation, returning null for the bitmap object but setting outWidth, outHeight and outMimeType. This technique allows you to read the dimensions and type of the image data prior to construction (and memory allocation) of the bitmap.
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.id.myimage, options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
String imageType = options.outMimeType;
To avoid java.lang.OutOfMemory exceptions, check the dimensions of a bitmap before decoding it.
STEP 2
To tell the decoder to subsample the image, loading a smaller version into memory, set inSampleSize to true in your BitmapFactory.Options object.
For example, an image with resolution 2048x1536 that is decoded with an inSampleSize of 4 produces a bitmap of approximately 512x384. Loading this into memory uses 0.75MB rather than 12MB for the full image.
Here’s a method to calculate a sample size value that is a power of two based on a target width and height:
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
public static int calculateInSampleSize(
BitmapFactory.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;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
Please read this link for details. http://developer.android.com/training/displaying-bitmaps/load-bitmap.html

Related

Xamarin Loading Bitmaps Efficiently For Gridview

So i saw this xamarin document about loading large bitmaps efficiently. Yet im struggling to implement it for the gridview.
https://developer.xamarin.com/recipes/android/resources/general/load_large_bitmaps_efficiently/
So how can we implement it for a gridview's adapter?
Thank you in the advance.
So how can we implement it for a gridview's adapter?
You can create a class(ThumbImageFactory below) to wrap all the functions mentioned in the document:
public class ThumbImageFactory
{
public readonly Context context;
public ThumbImageFactory(Context c)
{
context = c;
}
public static int CalculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight)
{
// Raw height and width of image
float height = options.OutHeight;
float width = options.OutWidth;
double inSampleSize = 1D;
if (height > reqHeight || width > reqWidth)
{
int halfHeight = (int)(height / 2);
int halfWidth = (int)(width / 2);
// Calculate a inSampleSize that is a power of 2 - the decoder will use a value that is a power of two anyway.
while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth)
{
inSampleSize *= 2;
}
}
return (int)inSampleSize;
}
public Bitmap LoadScaledDownBitmapForDisplay(Resources res, BitmapFactory.Options options, int reqWidth, int reqHeight,int resourceId)
{
// Calculate inSampleSize
options.InSampleSize = CalculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.InJustDecodeBounds = false;
return BitmapFactory.DecodeResource(res, resourceId, options);
}
public BitmapFactory.Options GetBitmapOptionsOfImage(int resourceId)
{
BitmapFactory.Options options = new BitmapFactory.Options
{
InJustDecodeBounds = true
};
// The result will be null because InJustDecodeBounds == true.
Bitmap result = BitmapFactory.DecodeResource(context.Resources, resourceId, options);
int imageHeight = options.OutHeight;
int imageWidth = options.OutWidth;
return options;
}
}
Create an ThumbImageFactory instance in your Adapter and call the functions in GetView:
public class ImageAdapter : BaseAdapter
{
private readonly Context context;
private ThumbImageFactory thumbFactory;
public ImageAdapter(Context c)
{
context = c;
thumbFactory = new ThumbImageFactory(c);
}
...
public override View GetView(int position, View convertView, ViewGroup parent)
{
ImageView imageView;
if (convertView == null)
{
imageView = new ImageView(this.context);
imageView.LayoutParameters = new AbsListView.LayoutParams(150, 150);
imageView.SetScaleType(ImageView.ScaleType.CenterCrop);
imageView.SetPadding(0, 0, 0, 0);
}
else
{
imageView = (ImageView)convertView;
}
Bitmap bitmap = GetThumbImage(thumbIds[position]);
imageView.SetImageBitmap(bitmap);
return imageView;
}
public Bitmap GetThumbImage(int resourceId)
{
BitmapFactory.Options options = thumbFactory.GetBitmapOptionsOfImage(resourceId);
Bitmap bitmap=thumbFactory.LoadScaledDownBitmapForDisplay(context.Resources, options, 150, 150, resourceId);
return bitmap;
}
}
Notes: we can't modify the GetView to async, so I changed all the functions in document to sync functions. Here is is complete Demo.

Gridview images mixed up on scroll

I'm trying to solve this issue about mixed up images in gridview when scrolling. I already saw similar posts here about this issue but unfortunately I didn't solve it yet.
I use asynctask to load the images in the gridView, and I have only imageView in the grid.
Thanks!
Here is my code:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ImageView img;
if (convertView == null) {
img = new ImageView(GalleryActivity.this);
WindowManager wm = (WindowManager) GalleryActivity.this.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
width = width / 3 - 4;
img.setLayoutParams(new AbsListView.LayoutParams(width, width));
img.setScaleType(ImageView.ScaleType.CENTER_CROP);
} else {
img = (ImageView) convertView;
}
File dics = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
File dir = new File(dics, "yyy");
if (!dir.exists() && !dir.mkdirs()) {
img.setImageResource(holder(position + 1));
} else {
String file_name = dir.getAbsolutePath() + "/" + (position + 1) + ".jpg";
if (new File(file_name).exists()) {
BitmapWorkerTask task = new BitmapWorkerTask(img);
task.execute(file_name);
items[position].setStatus(1);
} else {
img.setImageResource(holder(position + 1));
}
}
return img;
}
class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
private String data;
public BitmapWorkerTask(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
// Decode image in background.
#Override
protected Bitmap doInBackground(String... params) {
data = params[0];
return decodeSampledBitmapFromResource(data,100,100);
}
// Once complete, see if ImageView is still around and set bitmap.
#Override
protected void onPostExecute(Bitmap bitmap) {
if (imageViewReference != null && bitmap != null) {
final ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
}
}
public Bitmap decodeSampledBitmapFromResource(String resId,
int reqWidth, int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(resId,options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(resId);
}
public int calculateInSampleSize(
BitmapFactory.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;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
while ((halfHeight / inSampleSize) >= reqHeight
&& (halfWidth / inSampleSize) >= reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
The reason behind your problem is that the BitmapWorkerTask is not finished by starting order so it could override the newest result by older one.
To avoid this you have to keep one BitmapWorkerTask for each view and cancel the old one if it's still working so it doesn't override the result of the new BitmapWorkerTask
You can use setTag and getTag methods to achive this purpose and keep a reference of the latest BitmapWorkerTask working on each view.
You are not setting Tag to ImageView while starting image loading thread that why is set image to current one show at screen when thread completes it job .
you should pass some id as a parameter in BitmapWorkerTask class .

Using ASyncTask to Draw Bitmap

I followed the online tutorial and created a class like so:
public class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
private int data = 0;
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(Integer... params) {
data = params[0];
return decodeSampledBitmapFromResource(getResources(), data, 100, 100);
}
public Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
public int calculateInSampleSize(
BitmapFactory.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;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
// Once complete, see if ImageView is still around and set bitmap.
#Override
protected void onPostExecute(Bitmap bitmap) {
if (imageViewReference != null && bitmap != null) {
final ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
}
public void loadBitmap(int resId, ImageView imageView) {
BitmapWorkerTask task = new BitmapWorkerTask(imageView);
task.execute(resId);
}
}
Now that I created the "ASyncTask" class, I do not know how to apply it.
What I need to do is simple. I need to draw the bitmap like so (it is set up so that it will do it every second):
canvas.drawBitmap(myBitmap, centerX, centerY, null);
How do I apply ASyncTask now so that I will draw this bitmap without doing too much work on the thread? Please help, much appreciated.

LruCache not working with imageAdapter

I'm having 11 images in my resources. I use a GridView to display them.
Because images take a lot of space in my ImageAdapter class I calculate sample size and then decode the resouce as per the tutorial here to efficient load an image.
Before I return the decoded bitmap from decodeSampledBitmapFromResource I'm adding the bitmap to LruCache :
Bitmap b = BitmapFactory.decodeResource(res, resId, options);
String key = Integer.toString(resId);
// Log.i("byte", "b.getByteCount()==" + b.getByteCount());
addBitmapToMemoryCache(key, b); //add to cache
which leads to my getView() to try and get cached bitmap if it's not null - else use the method I mentioned above.
For adding and getting bitmaps from cache I'm using :
public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
if (getBitmapFromMemCache(key) == null) {
Log.i("addbitmaptocache", "Add key= " + key);
mMemoryCache.put(key, bitmap);
}
}
public Bitmap getBitmapFromMemCache(String key) {
Log.i("getbitmaptocache", "GET KEY= " + key);
return mMemoryCache.get(key);
}
What happens is that if ( cachedBitmap != null ) is never true which makes me believe something is wrong.
full code for the class :
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private int wid;
private static final String AdapterTAG="adapterTAG";
// private ImageView imageView;
private Bitmap mBitmap;
private LruCache<String, Bitmap> mMemoryCache;
public ImageAdapter(Context c, int wid) {
mContext = c;
this.wid = wid;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolderItem viewHolder;
int new_width = wid/2;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.grid_item, parent, false);
// well set up the ViewHolder
viewHolder = new ViewHolderItem();
viewHolder.textViewItem = (TextView) convertView.findViewById(R.id.textId);
viewHolder.imageViewItem = (ImageView) convertView.findViewById(R.id.imageId);
// store the holder with the view.
convertView.setTag(viewHolder);
} else{
viewHolder = (ViewHolderItem) convertView.getTag();
}
/** ******************** Caching ******************** **/
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
// Log.i("max", "maxMemory== " + maxMemory );
// Use 1/8th of the available memory for this memory cache.
final int cacheSize = maxMemory / 4;
// Log.i("cachesize", "cachesize== " + cacheSize);
mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
#Override
protected int sizeOf(String key, Bitmap bitmap) {
return bitmap.getByteCount() / 1024;
}
};
//Log.i("mMemoryCache", "mMemoryCache= " + mMemoryCache);
viewHolder.textViewItem.setId(position);
viewHolder.imageViewItem.getLayoutParams().width = new_width -5;
viewHolder.imageViewItem.getLayoutParams().height = new_width -5;
viewHolder.imageViewItem.setScaleType(ImageView.ScaleType.CENTER_CROP);
viewHolder.imageViewItem.setPadding(0, 0, 0, 0);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
final String imageKey = String.valueOf(mThumbIds[position]);
final Bitmap cachedBitmap = getBitmapFromMemCache(imageKey); // use cached Bitmap or ... decode
if ( cachedBitmap != null ) {
Log.i("cached", "CACHED BITMAP FOR THE WIN!!!!");
viewHolder.imageViewItem.setImageBitmap(cachedBitmap);
} else {
viewHolder.imageViewItem.setImageBitmap(decodeSampledBitmapFromResource(mContext.getResources(), mThumbIds[position] , new_width, 200));
}
return convertView;
}
static class ViewHolderItem {
TextView textViewItem;
ImageView imageViewItem;
}
// references to our images
private Integer[] mThumbIds = {
R.drawable.wallpaper0, R.drawable.wallpaper1,
R.drawable.wallpaper2, R.drawable.wallpaper3,
R.drawable.wallpaper4, R.drawable.wallpaper5,
R.drawable.wallpaper6, R.drawable.wallpaper7,
R.drawable.wallpaper8, R.drawable.wallpaper9,
R.drawable.wallpaper10
};
public Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// Log.i("req", "reqWidth= " + reqWidth + " reqHeight=" + reqHeight ); // params
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
String imageType = options.outMimeType;
Log.i("options", "Width== " + imageWidth + " Height== " + imageHeight + " Type== " + imageType );
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inPurgeable = true;
options.inInputShareable = true;
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap b = BitmapFactory.decodeResource(res, resId, options);
String key = Integer.toString(resId);
// Log.i("byte", "b.getByteCount()==" + b.getByteCount());
addBitmapToMemoryCache(key, b); //add to cache
return b;
}
public static int calculateInSampleSize(BitmapFactory.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;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
Log.i("sample", "size=" +inSampleSize );
return inSampleSize;
}
public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
if (getBitmapFromMemCache(key) == null) {
Log.i("addbitmaptocache", "Add key= " + key);
mMemoryCache.put(key, bitmap);
}
}
public Bitmap getBitmapFromMemCache(String key) {
Log.i("getbitmaptocache", "GET KEY= " + key);
return mMemoryCache.get(key);
}
}
You should not be instantiating the mMemoryCache in the getView() method. Place that in the constructor. That's why it can never find the bitmap in cache, because you are constantly destroying and recreating it.

outOfMemory when loading images ListView

I download photos from the Internet. have a site on the same page which has 18 photos (80x60 px ~ 10kb).
so I made ​​a list which loads the new picture (sleduyuschuyuyu page)
the problem is when I load three or more pages, a memory error occurs
the question is how to get rid of?
Now I build an array of bitmaps
for (Element titles : title) {
if (titles.children().hasClass("btl")){
m = new HashMap<String, Object>();
m.put(MyActivity.ATTRIBUTE_NAME_TEXT, titles.select("a[href]").attr("abs:href"));
Picasso p = Picasso.with(MyActivity.context);
m.put(MyActivity.ATTRIBUTE_NAME_PHOTO,Bitmap.createScaledBitmap(p.load(titles.select("img").attr("abs:src")).get(),80,60, true) );
data.add(m);
}
}
and in adapter
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
final Map<String, Object> itemData = datas.get(position*2);
final Map<String, Object> itemData2 = datas.get(position*2+1);
Bitmap bitmap2 = null;
Bitmap bitmap = (Bitmap) itemData.get("img");
if(itemData2!=null)
bitmap2 = (Bitmap) itemData2.get("img");
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.items, null, true);
holder = new ViewHolder();
holder.ivImage = (ImageView) rowView.findViewById(R.id.imageView);
holder.ivImage2 = (ImageView) rowView.findViewById(R.id.imageView1);
rowView.setTag(holder);
} else {
holder = (ViewHolder) rowView.getTag();
}
holder.ivImage.setImageBitmap(bitmap);
holder.ivImage2.setImageBitmap(bitmap2);
holder.ivImage.setTag(position*2);
holder.ivImage2.setTag(position*2+1);
holder.ivImage.setOnClickListener(this);
holder.ivImage2.setOnClickListener(this);
return rowView;
}
I was offered to save images in the cache and load them from there but do not know how to do it.
please help
Use disk cache... This article also has plenty of other useful tips for loading bitmaps
http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html#disk-cache
The best way to load iomages is the picasso library at http://square.github.io/picasso/
You will read the images by using decoding the images to your desired size....
Convert the image into like this method....
It's used for drawable resources....
Bitmap bmap2 = decodeSampledBitmapFromResource(getResources(),
R.drawable.hydrangeas, width, height);
public static Bitmap decodeSampledBitmapFromResource(Resources res,
int resId, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
public static int calculateInSampleSize(BitmapFactory.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;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and
// keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
Which the below method for decode by the use of streams....
public static Bitmap decodeSampledBitmapFromResource(InputStream in,
int reqWidth, int reqHeight) throws IOException {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
in.mark(in.available());
BitmapFactory.decodeStream(in, null, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
in.reset();
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeStream(in, null, options);
}
Suppose you will get fail in the all method You will try this logic you just need to add this line into your mainfest file...
You just need to add this line to your manifest file. It will allocate the large memory for your application.
android:largeHeap="true"

Categories

Resources