- Notifications
You must be signed in to change notification settings - Fork0
Powerful and flexible library for loading, caching and displaying images on Android.
License
coder92/Android-Universal-Image-Loader
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
This project aims to provide a reusable instrument for asynchronous image loading, caching and displaying. It is originally based onFedor Vlasov's project and has been vastly refactored and improved since then.
Upcoming changes in new UIL version (1.9.2)
- Possibility to call ImageLoader out of UI thread
- New Disk Cache API (more flexible). New
LruDiscCachebased on Jake Wharton'sDiskLruCache.
- Multithread image loading
- Possibility of wide tuning ImageLoader's configuration (thread executors, downloader, decoder, memory and disc cache, display image options, and others)
- Possibility of image caching in memory and/or on device's file system (or SD card)
- Possibility to "listen" loading process
- Possibility to customize every display image call with separated options
- Widget support
Android 2.0+ support
- universal-image-loader-1.9.1.jar (library; contains *.class files)
- universal-image-loader-1.9.1-sources.jar (sources; contains *.java files)
- universal-image-loader-1.9.1-javadoc.jar (Java docs; contains *.html files)
- universal-image-loader-1.9.1-with-sources.jar (library with sources inside; contains *.class and *.java files)
Prefer to use this JAR so you can see Java docs in Eclipse tooltips. - universal-image-loader-sample-1.9.1.apk (sample application)
Latest snapshot of the library -here
- Universal Image Loader. Part 1 - Introduction [RU]
- Universal Image Loader. Part 2 - Configuration [RU |EN]
- Universal Image Loader. Part 3 - Usage [RU |EN]
- Look intoUseful Info
- Search problem solution onStackOverFlow
- Ask your own question onStackOverFlow.
Be sure to mention following information in your question:
- UIL version (e.g. 1.9.1)
- Android version tested on (e.g. 2.1)
- your configuration (
ImageLoaderConfiguration) - display options (
DisplayImageOptions) getView()method code of your adapter (if you use it)- XML layout of your ImageView you load image into
Bugs andfeature requests puthere.
If you have someissues on migration to newer library version - be sure to ask for helphere
Manual:
- Download JAR
- Put the JAR in thelibs subfolder of your Android project
or
Maven dependency:
<dependency><groupId>com.nostra13.universalimageloader</groupId><artifactId>universal-image-loader</artifactId><version>1.9.1</version></dependency>
<manifest><uses-permissionandroid:name="android.permission.INTERNET" /><!-- Include next permission if you want to allow UIL to cache images on SD card--><uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE" />...<applicationandroid:name="MyApplication">...</application></manifest>
publicclassMyApplicationextendsApplication {@OverridepublicvoidonCreate() {super.onCreate();// Create global configuration and initialize ImageLoader with this configurationImageLoaderConfigurationconfig =newImageLoaderConfiguration.Builder(getApplicationContext())....build();ImageLoader.getInstance().init(config);}}
- ImageLoaderConfiguration (
ImageLoaderConfiguration) is global for application. - Display Options (
DisplayImageOptions) are local for every display task (ImageLoader.displayImage(...)).
All options in Configuration builder are optional. Use only those you really want to customize.
See default values for config options in Java docs for every option.
// DON'T COPY THIS CODE TO YOUR PROJECT! This is just example of ALL options using.FilecacheDir =StorageUtils.getCacheDirectory(context);ImageLoaderConfigurationconfig =newImageLoaderConfiguration.Builder(context).memoryCacheExtraOptions(480,800)// default = device screen dimensions.discCacheExtraOptions(480,800,CompressFormat.JPEG,75,null).taskExecutor(...).taskExecutorForCachedImages(...).threadPoolSize(3)// default.threadPriority(Thread.NORM_PRIORITY -1)// default.tasksProcessingOrder(QueueProcessingType.FIFO)// default.denyCacheImageMultipleSizesInMemory().memoryCache(newLruMemoryCache(2 *1024 *1024)).memoryCacheSize(2 *1024 *1024).memoryCacheSizePercentage(13)// default.discCache(newUnlimitedDiscCache(cacheDir))// default.discCacheSize(50 *1024 *1024).discCacheFileCount(100).discCacheFileNameGenerator(newHashCodeFileNameGenerator())// default.imageDownloader(newBaseImageDownloader(context))// default.imageDecoder(newBaseImageDecoder())// default.defaultDisplayImageOptions(DisplayImageOptions.createSimple())// default.writeDebugLogs().build();
Display Options can be applied to every display task (ImageLoader.displayImage(...) call).
Note: If Display Options wasn't passed toImageLoader.displayImage(...)method then default Display Options from configuration (ImageLoaderConfiguration.defaultDisplayImageOptions(...)) will be used.
// DON'T COPY THIS CODE TO YOUR PROJECT! This is just example of ALL options using.DisplayImageOptionsoptions =newDisplayImageOptions.Builder().showImageOnLoading(R.drawable.ic_stub)// resource or drawable.showImageForEmptyUri(R.drawable.ic_empty)// resource or drawable.showImageOnFail(R.drawable.ic_error)// resource or drawable.resetViewBeforeLoading(false)// default.delayBeforeLoading(1000).cacheInMemory(false)// default.cacheOnDisc(false)// default.preProcessor(...).postProcessor(...).extraForDownloader(...).considerExifParams(false)// default.imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)// default.bitmapConfig(Bitmap.Config.ARGB_8888)// default.decodingOptions(...).displayer(newSimpleBitmapDisplayer())// default.handler(newHandler())// default.build();
StringimageUri ="http://site.com/image.png";// from WebStringimageUri ="file:///mnt/sdcard/image.png";// from SD cardStringimageUri ="content://media/external/audio/albumart/13";// from content providerStringimageUri ="assets://image.png";// from assetsStringimageUri ="drawable://" +R.drawable.image;// from drawables (only images, non-9patch)
NOTE: Usedrawable:// only if you really need it! Alwaysconsider the native way to load drawables -ImageView.setImageResource(...) instead of using ofImageLoader.
// Load image, decode it to Bitmap and display Bitmap in ImageView (or any other view//which implements ImageAware interface)imageLoader.displayImage(imageUri,imageView);
// Load image, decode it to Bitmap and return Bitmap to callbackimageLoader.loadImage(imageUri,newSimpleImageLoadingListener() {@OverridepublicvoidonLoadingComplete(StringimageUri,Viewview,BitmaploadedImage) {// Do whatever you want with Bitmap}});
// Load image, decode it to Bitmap and return Bitmap synchronouslyBitmapbmp =imageLoader.loadImageSync(imageUri);
// Load image, decode it to Bitmap and display Bitmap in ImageView (or any other view//which implements ImageAware interface)imageLoader.displayImage(imageUri,imageView,displayOptions,newImageLoadingListener() {@OverridepublicvoidonLoadingStarted(StringimageUri,Viewview) {...}@OverridepublicvoidonLoadingFailed(StringimageUri,Viewview,FailReasonfailReason) {...}@OverridepublicvoidonLoadingComplete(StringimageUri,Viewview,BitmaploadedImage) {...}@OverridepublicvoidonLoadingCancelled(StringimageUri,Viewview) {...}},newImageLoadingProgressListener() {@OverridepublicvoidonProgressUpdate(StringimageUri,Viewview,intcurrent,inttotal) {...}});
// Load image, decode it to Bitmap and return Bitmap to callbackImageSizetargetSize =newImageSize(120,80);// result Bitmap will be fit to this sizeimageLoader.loadImage(imageUri,targetSize,displayOptions,newSimpleImageLoadingListener() {@OverridepublicvoidonLoadingComplete(StringimageUri,Viewview,BitmaploadedImage) {// Do whatever you want with Bitmap}});
// Load image, decode it to Bitmap and return Bitmap synchronouslyImageSizetargetSize =newImageSize(120,80);// result Bitmap will be fit to this sizeBitmapbmp =imageLoader.loadImageSync(imageUri,targetSize,displayOptions);
Other useful methods and classes to consider.
ImageLoader || - getMemoryCache()| - clearMemoryCache()| - getDiscCache()| - clearDiscCache()| - denyNetworkDownloads(boolean)| - handleSlowNetwork(boolean)| - pause()| - resume()| - stop()| - destroy()| - getLoadingUriForView(ImageView)| - getLoadingUriForView(ImageAware)| - cancelDisplayTask(ImageView)| - cancelDisplayTask(ImageAware)MemoryCacheUtil || - findCachedBitmapsForImageUri(...)| - findCacheKeysForImageUri(...)| - removeFromCache(...)DiscCacheUtil | | - findInCache(...) | - removeFromCache(...)StorageUtils | | - getCacheDirectory(Context) | - getIndividualCacheDirectory(Context) | - getOwnCacheDirectory(Context, String)PauseOnScrollListenerImageAware | | - getWidth() | - getHeight() | - getScaleType() | - getWrappedView() | - isCollected() | - getId() | - setImageDrawable(Drawable) | - setImageBitmap(Bitmap)
Also look into more detailedLibrary Map
- Caching is NOT enabled by default. If you want loaded images will be cached in memory and/or on disc then you should enable caching in DisplayImageOptions this way:
// Create default options which will be used for every// displayImage(...) call if no options will be passed to this methodDisplayImageOptionsdefaultOptions =newDisplayImageOptions.Builder()... .cacheInMemory(true) .cacheOnDisc(true) ... .build();ImageLoaderConfigurationconfig =newImageLoaderConfiguration.Builder(getApplicationContext()) ... .defaultDisplayImageOptions(defaultOptions) ... .build();ImageLoader.getInstance().init(config);// Do it on Application start
// Then later, when you want to display imageImageLoader.getInstance().displayImage(imageUrl,imageView);// Default options will be used
or this way:
DisplayImageOptionsoptions =newDisplayImageOptions.Builder()... .cacheInMemory(true) .cacheOnDisc(true) ... .build();ImageLoader.getInstance().displayImage(imageUrl,imageView,options);// Incoming options will be used
- If you enabled disc caching then UIL try to cache images on external storage (/sdcard/Android/data/[package_name]/cache). If external storage is not available then images are cached on device's filesystem.To provide caching on external storage (SD card) add following permission to AndroidManifest.xml:
<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
- How UIL define Bitmap size needed for exact ImageView? It searches defined parameters:
- Get actual measured width and height of ImageView
- Get
android:layout_widthandandroid:layout_heightparameters - Get
android:maxWidthand/orandroid:maxHeightparameters - Get maximum width and/or height parameters from configuration (
memoryCacheExtraOptions(int, int)option) - Get width and/or height of device screen
Sotry to setandroid:layout_width|android:layout_height orandroid:maxWidth|android:maxHeight parameters for ImageView if you know approximate maximum size of it. It will help correctly compute Bitmap size needed for this view andsave memory.
- If you often gotOutOfMemoryError in your app using Universal Image Loader then try next (all of them or several):
- Reduce thread pool size in configuration (
.threadPoolSize(...)). 1 - 5 is recommended. - Use
.bitmapConfig(Bitmap.Config.RGB_565)in display options. Bitmaps in RGB_565 consume 2 times less memory than in ARGB_8888. - Use
.memoryCache(new WeakMemoryCache())in configuration or disable caching in memory at all in display options (don't call.cacheInMemory()). - Use
.imageScaleType(ImageScaleType.IN_SAMPLE_INT)in display options. Or try.imageScaleType(ImageScaleType.EXACTLY).
- For memory cache configuration (
ImageLoaderConfiguration.memoryCache(...)) you can use already prepared implementations.
- Cache usingonly strong references:
LruMemoryCache(Least recently used bitmap is deleted when cache size limit is exceeded) -Used by default
- Caches usingweak and strong references:
UsingFreqLimitedMemoryCache(Least frequently used bitmap is deleted when cache size limit is exceeded)LRULimitedMemoryCache(Least recently used bitmap is deleted when cache size limit is exceeded)FIFOLimitedMemoryCache(FIFO rule is used for deletion when cache size limit is exceeded)LargestLimitedMemoryCache(The largest bitmap is deleted when cache size limit is exceeded)LimitedAgeMemoryCache(Decorator. Cached object is deleted when its age exceeds defined value)
- Cache usingonly weak references:
WeakMemoryCache(Unlimited cache)
- For disc cache configuration (
ImageLoaderConfiguration.discCache(...)) you can use already prepared implementations:
UnlimitedDiscCache(The fastest cache, doesn't limit cache size) -Used by defaultTotalSizeLimitedDiscCache(Cache limited by total cache size. If cache size exceeds specified limit then file with the most oldest last usage date will be deleted)FileCountLimitedDiscCache(Cache limited by file count. If file count in cache directory exceeds specified limit then file with the most oldest last usage date will be deleted. Use it if your cached files are of about the same size.)LimitedAgeDiscCache(Size-unlimited cache with limited files' lifetime. If age of cached file exceeds defined limit then it will be deleted from cache.)
NOTE: UnlimitedDiscCache is 30%-faster than other limited disc cache implementations.
- To display bitmap (
DisplayImageOptions.displayer(...)) you can use already prepared implementations:
RoundedBitmapDisplayer(Displays bitmap with rounded corners)FadeInBitmapDisplayer(Displays image with "fade in" animation)
- To avoid list (grid, ...) scrolling lags you can use
PauseOnScrollListener:
booleanpauseOnScroll =false;// or truebooleanpauseOnFling =true;// or falsePauseOnScrollListenerlistener =newPauseOnScrollListener(imageLoader,pauseOnScroll,pauseOnFling);listView.setOnScrollListener(listener);
- If you see in logs some strange supplement at the end of image URL (e.g.
http://anysite.com/images/image.png_230x460) then it doesn't mean this URL is used in requests. This is just "URL + target size", also this is key for Bitmap in memory cache. This postfix (_230x460) isNOT used in requests.
MediaHouse, UPnP/DLNA Browser |Prezzi Benzina (AndroidFuel) |ROM Toolbox Lite,Pro |Stadium Astro |Chef Astro |Sporee - Live Soccer Scores |EyeEm - Photo Filter Camera |PhotoDownloader for Facebook |Topface - meeting is easy |reddit is fun |Diaro - personal diary |WebMoney Keeper Mobile |LoL Memento League of Legends |Meetup |Vingle - Magazines by Fans |Anime Music Radio |WidgetLocker Theme Viewer |ShortBlogger for Tumblr |SnapDish Food Camera |Twitch |TVShow Time, TV show guide |Planning Center Services |Daybe - 일기가 되는 SNS |Lapse It |My Cloud Player for SoundCloud |SoundTracking |LoopLR Social Video |Reddit Pics HD |Hír24 |Immobilien Scout24 |Lieferheld - Pizza Pasta Sushi |Loocator: free sex datings |벨팡-개편 이벤트,컬러링,벨소리,무료,최신가요,링투유 |Streambels AirPlay/DLNA Player |Ship Mate - All Cruise Lines |Disk & Storage Analyzer
You can support the project and thank the author for his hard work :)
If you use Universal Image Loader code in your application you should inform the author about it (email: nostra13[at]gmail[dot]com ) like this:
Subject: UIL usage notification
Text: I use Universal Image Loader <lib_version> in <application_name> - http://link_to_google_play.I [allow | don't allow] to mention my app in section "Applications using Universal Image Loader" on GitHub.
Also I'll be grateful if you mention UIL in application UI with string"Using Universal Image Loader (c) 2011-2014, Sergey Tarasevich" (e.g. in some "About" section).
Copyright 2011-2014 Sergey TarasevichLicensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governing permissions andlimitations under the License.About
Powerful and flexible library for loading, caching and displaying images on Android.
Resources
License
Uh oh!
There was an error while loading.Please reload this page.



