Xamarin Loading Bitmaps Efficiently For Gridview - android

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.

Related

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 .

Android Image taking a long time to get from URL

Currently i'm loading images from a url and it is taking way to long and i cannot work out why, sometimes taking longer than 60 seconds to get images that aren't really that big.
My Code:
Get image async task:
public class GetImageAsyncTask extends AsyncTask<Void, Void, Bitmap> {
String url;
OnImageRetrieved listener;
ImageView imageView;
int height;
int width;
public GetImageAsyncTask(String url, ImageView imageView,OnImageRetrieved listener, int height, int width) {
this.url = url;
this.listener = listener;
this.imageView = imageView;
this.height = height;
this.width = width;
}
public interface OnImageRetrieved {
void onImageRetrieved(Bitmap image, ImageView imageview, String url);
}
protected Bitmap doInBackground(Void... params) {
Bitmap image = null;
try {
image = ImageUtilities.decodeSampledBitmapFromUrl(this.url, this.width, this.height);
} catch (Exception e) {
e.printStackTrace();
}
return image;
}
protected void onPostExecute(Bitmap result) {
this.listener.onImageRetrieved(result, this.imageView, this.url);
}
}
public static Bitmap decodeSampledBitmapFromUrl(String url, int reqWidth, int reqHeight) throws IOException {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new java.net.URL(url).openStream(), null, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeStream(new java.net.URL(url).openStream(), null, options);
}
Getting sample size:
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
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;
}
These methods are used because of memory complications that can arise if not, but the time it seems to take is just to long. Is there some very heavy computation that i'm just not seeing or?
you can use Picasso or volly library to load image.I suggest volly to use because its introduce by google itself.
So the problem stems from the array adapter and the fact that getView() can be called 100's of times which can be close to 100mb of data is being downloaded simultaneously.
So as a temp fix for this situation i implemented a global LruCache singleton, that i first check before starting the async task.
This is clearly not ideal but it will have to do for now. Im sure there are better solutions out there and i would love to hear them if anyone has one to offer.

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.

java.lang.OutOfMemoryError while display the images in gallery

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

Gallery app, if Selected photos width large to height, photos seems vertical

I try a gallery app.
My app working 2 diffrent form.
From the Gallery or from camera selection,
if selected photos height large to width everything ok.
if Selected photos width large to height, photos seems vertical
Example,
This image width : 3264, height : 2448
My app in seems like this;
this is my decode size code, Sorry bad english, thank you.
private class DecodeSize extends AsyncTask<String,Void,Bitmap> {
private int reqWidth;
private int reqHeight;
private ImageView imageView;
private final WeakReference<ImageView> imageViewReference;
private DecodeSize(int reqWidth, int reqHeight, ImageView imageView) {
this.reqWidth = reqWidth;
this.reqHeight = reqHeight;
this.imageViewReference = new WeakReference<ImageView>(imageView);
}
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;
}
#Override
protected Bitmap doInBackground(String... params) {
String photo_path = params[0];
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(photo_path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(photo_path, options);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if(imageViewReference != null && bitmap !=null) {
final ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
}
}
private void decodeSizeFunction(String picturePath) {
decodeSize = new DecodeSize(200,200,foto_image);
decodeSize.execute(picturePath);
}

Categories

Resources