Share Coding

Tutorials, Problems, Stuffs …

Android ‘Out of memory’ when loading image

To solve ‘Out of memory’ when loading image, you must control the image size and image quality.
This article are go to solve the problem of out of memory when loading a huge image into a image view.

Besides, it provide lazy load automatically.

Universal Image Loader
Home page of Universal Image Loader

Install by config build.gradle(Module):

dependencies {
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.4'
}

 

In MyApplication class(Your custom Application class), onCreate(), write down:

// UNIVERSAL IMAGE LOADER SETUP
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
        .cacheOnDisc(true).cacheInMemory(true)
        .imageScaleType(ImageScaleType.EXACTLY)
        .displayer(new FadeInBitmapDisplayer(300)).build();

ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
        getApplicationContext())
        .defaultDisplayImageOptions(defaultOptions)
        .memoryCache(new WeakMemoryCache())
        .discCacheSize(100 * 1024 * 1024).build();

ImageLoader.getInstance().init(config);
// END - UNIVERSAL IMAGE LOADER SETUP

In your activity, use the following code to load image:

File imgFile = new File(ImageUtility.getSnapShotDirectoryPath() + path);
ImageView imgSnapShotFull = (ImageView) findViewById(R.id.imgSnapShotFull);
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage("file://" + imgFile.getAbsolutePath(), imgSnapShotFull);

You can control the cache size or sample size to do a advanced loading.
Please follow the instruction at the Home page.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: