Step 1. Add the JitPack repository to your build file
Add it in your root build.gradle at the end of repositories:
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
mavenCentral()
maven { url 'https://jitpack.io' }
}
}
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
Add it in your build.sbt at the end of resolvers:
resolvers += "jitpack" at "https://jitpack.io"
Add it in your project.clj at the end of repositories:
:repositories [["jitpack" "https://jitpack.io"]]
Step 2. Add the dependency
dependencies {
implementation 'com.github.imoblife:Android-Universal-Image-Loader:v1.8.6'
}
<dependency>
<groupId>com.github.imoblife</groupId>
<artifactId>Android-Universal-Image-Loader</artifactId>
<version>v1.8.6</version>
</dependency>
libraryDependencies += "com.github.imoblife" % "Android-Universal-Image-Loader" % "v1.8.6"
:dependencies [[com.github.imoblife/Android-Universal-Image-Loader "v1.8.6"]]
This project aims to provide a reusable instrument for asynchronous image loading, caching and displaying. It is originally based on Fedor Vlasov's project and has been vastly refactored and improved since then.
Upcoming changes in new UIL version (1.9.2)
LruDiscCache
based on Jake Wharton's DiskLruCache
.Android 2.0+ support
Latest snapshot of the library - here
ImageLoaderConfiguration
)DisplayImageOptions
)getView()
method code of your adapter (if you use it)Bugs and feature requests put here.<br /> If you have some issues on migration to newer library version - be sure to ask for help here
Manual:
or
Maven dependency:
<dependency>
<groupId>com.nostra13.universalimageloader</groupId>
<artifactId>universal-image-loader</artifactId>
<version>1.9.1</version>
</dependency>
<manifest>
<uses-permission android:name="android.permission.INTERNET" />
<!-- Include next permission if you want to allow UIL to cache images on SD card -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
<application android:name="MyApplication">
...
</application>
</manifest>
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
// Create global configuration and initialize ImageLoader with this configuration
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
...
.build();
ImageLoader.getInstance().init(config);
}
}
ImageLoaderConfiguration
) is global for application.DisplayImageOptions
) are local for every display task (ImageLoader.displayImage(...)
).All options in Configuration builder are optional. Use only those you really want to customize.<br />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.
File cacheDir = StorageUtils.getCacheDirectory(context);
ImageLoaderConfiguration config = new ImageLoaderConfiguration.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(new LruMemoryCache(2 * 1024 * 1024))
.memoryCacheSize(2 * 1024 * 1024)
.memoryCacheSizePercentage(13) // default
.discCache(new UnlimitedDiscCache(cacheDir)) // default
.discCacheSize(50 * 1024 * 1024)
.discCacheFileCount(100)
.discCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
.imageDownloader(new BaseImageDownloader(context)) // default
.imageDecoder(new BaseImageDecoder()) // 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 to ImageLoader.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.
DisplayImageOptions options = new DisplayImageOptions.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(new SimpleBitmapDisplayer()) // default
.handler(new Handler()) // default
.build();
String imageUri = "http://site.com/image.png"; // from Web
String imageUri = "file:///mnt/sdcard/image.png"; // from SD card
String imageUri = "content://media/external/audio/albumart/13"; // from content provider
String imageUri = "assets://image.png"; // from assets
String imageUri = "drawable://" + R.drawable.image; // from drawables (only images, non-9patch)
NOTE: Use drawable://
only if you really need it! Always consider the native way to load drawables - ImageView.setImageResource(...)
instead of using of ImageLoader
.
// 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 callback
imageLoader.loadImage(imageUri, new SimpleImageLoadingListener() {
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
// Do whatever you want with Bitmap
}
});
// Load image, decode it to Bitmap and return Bitmap synchronously
Bitmap bmp = 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, new ImageLoadingListener() {
@Override
public void onLoadingStarted(String imageUri, View view) {
...
}
@Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
...
}
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
...
}
@Override
public void onLoadingCancelled(String imageUri, View view) {
...
}
}, new ImageLoadingProgressListener() {
@Override
public void onProgressUpdate(String imageUri, View view, int current, int total) {
...
}
});
// Load image, decode it to Bitmap and return Bitmap to callback
ImageSize targetSize = new ImageSize(120, 80); // result Bitmap will be fit to this size
imageLoader.loadImage(imageUri, targetSize, displayOptions, new SimpleImageLoadingListener() {
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
// Do whatever you want with Bitmap
}
});
// Load image, decode it to Bitmap and return Bitmap synchronously
ImageSize targetSize = new ImageSize(120, 80); // result Bitmap will be fit to this size
Bitmap bmp = imageLoader.loadImageSync(imageUri, targetSize, displayOptions);
Other useful methods and classes to consider.
<pre> 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) PauseOnScrollListener ImageAware | | - getWidth() | - getHeight() | - getScaleType() | - getWrappedView() | - isCollected() | - getId() | - setImageDrawable(Drawable) | - setImageBitmap(Bitmap) </pre>Also look into more detailed Library Map
// Create default options which will be used for every
// displayImage(...) call if no options will be passed to this method
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
...
.cacheInMemory(true)
.cacheOnDisc(true)
...
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
...
.defaultDisplayImageOptions(defaultOptions)
...
.build();
ImageLoader.getInstance().init(config); // Do it on Application start
// Then later, when you want to display image
ImageLoader.getInstance().displayImage(imageUrl, imageView); // Default options will be used
or this way:
DisplayImageOptions options = new DisplayImageOptions.Builder()
...
.cacheInMemory(true)
.cacheOnDisc(true)
...
.build();
ImageLoader.getInstance().displayImage(imageUrl, imageView, options); // Incoming options will be used
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
How UIL define Bitmap size needed for exact ImageView? It searches defined parameters:
android:layout_width
and android:layout_height
parametersandroid:maxWidth
and/or android:maxHeight
parametersmemoryCacheExtraOptions(int, int)
option)So try to set android:layout_width
|android:layout_height
or android: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 and save memory.
If you often got OutOfMemoryError in your app using Universal Image Loader then try next (all of them or several):
.threadPoolSize(...)
). 1 - 5 is recommended..bitmapConfig(Bitmap.Config.RGB_565)
in display options. Bitmaps in RGB_565 consume 2 times less memory than in ARGB_8888..memoryCache(new WeakMemoryCache())
in configuration or disable caching in memory at all in display options (don't call .cacheInMemory()
)..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.
LruMemoryCache
(Least recently used bitmap is deleted when cache size limit is exceeded) - Used by defaultUsingFreqLimitedMemoryCache
(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)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
:
boolean pauseOnScroll = false; // or true
boolean pauseOnFling = true; // or false
PauseOnScrollListener listener = new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling);
listView.setOnScrollListener(listener);
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
) is NOT used in requests.MediaHouse, UPnP/DLNA Browser | Деловой Киров | Бизнес-завтрак | Menu55 | SpokenPic | Kumir | TuuSo Image Search | Газета Стройка | Prezzi Benzina (AndroidFuel) | [Quiz Guess The Guy] (https://play.google.com/store/apps/details?id=com.game.guesstheguy) | Volksempfänger (alpha) | ROM Toolbox Lite, Pro | London 2012 Games | 카톡 이미지 - 예쁜 프로필 이미지 | dailyPen | Mania! | Stadium Astro | Chef Astro | Lafemme Fashion Finder | FastPaleo | Sporee - Live Soccer Scores | friendizer | LowPrice lowest book price | bluebee | EyeEm - Photo Filter Camera | Festival Wallpaper | Gaudi Hall | Spocal | PhotoDownloader for Facebook | Вкладыши | Dressdrobe | mofferin | WordBoxer | EZ Imgur | Ciudad en línea | Urbanismo en línea | Waypost | Moonrise Kingdom Wallpapers HD | Chic or Shock? | Auto Wallpapers | Brasil Notícias | ProfiAuto’s VideoBlog | CarteleraApp (Cine), AdsFree | Listonic - Zamów Zakupy | Topface - meeting is easy | Name The Meme | Name The World | Pregnancy Tickers - Widget | User Manager ROOT Android 4.2 | Theke | SensibleJournal | PiCorner for Flickr, Instagram | Survey-n-More - Paid Surveys | STROBEL Verlag Basic | reddit is fun, golden platinum | iDukan Diet Tracker | Geek Hero Comic | Sprinter | Twxter | Locaside ★ Parties und Events | fileboost | Urbanoe Mobile | What Channel's the Game On...? | MythTV Android Frontend | Diaro - personal diary | AwwBrowser | KCCO Pro | STQRY | Forbes Reader Holo | Pönis Filmclub | Socially You - Free, PRO | КПРФ.ру | Moment.me | Colonial Club | Plex for PlexPass | Perfect Spot | My Diet Tracker | All Cebu | WebMoney Keeper Mobile | Ja, Rock! | Art Widget, Pro | Le Monde Archives | LoL Memento League of Legends | WANNA B! 워너비! | Alcázar de San Juan | PetsDaily | CarCrazee | Meetup | G'day Australia (Newspapers) | Vingle - Magazines by Fans | Facebook Album Downloader | Esplorea | Dog Breeds | 롱비치하우스 펜션 - 을왕리해수욕장 | DJ Paolo | @to Music - VK, Last.fm, Radio | 배달몬스터-주문하고 로또받자(특허출원) | Extra! Newspaper Covers | iWestern | All is Wall - HD Wallpapers | Galbijjim Searcher | Slow Radio Unofficial | Protein Finder | Robird | MPme Radio | MicroHealth Hemofilia | Anime Music Radio | Top Games | 米折-购物省钱助手,淘宝网天猫聚划算京东等600商城返利 | Learn 'n' Share | ЯП.Мобайл | AssamKart | Da Ai TV | watch.is | HDOut | UsedAppleJuice | Killermatch - tennis, squash.. | FreeMusic | ScialaMundi | FRIENDSCOUT24 - FLIRT & DATING | Meteociel | ニコニコ静画(電子書籍) | Dota2TV | Sale Alert (Malaysia) | MMA Follower | WidgetLocker Theme Viewer | Rio de Janeiro Guide | Glassy Pro | Time to Surf | Страж | Gifstory - Gif Maker App | PHOTO MANIA | Emit | NSK | YogTube - Yogscast Tube | Echo Music Player | Amazon Money Saver | MmYear100 (Myanmar Calendar) | 笑える無料漫画の投稿アプリCOSMO(コスモ) | Drunker's Helper | Atlas grzybów | ShortBlogger for Tumblr | ShopLove - Shopping & Kataloge | Pubs and Bars Manaus | Select | Bokpuffen | Terapia Coletiva | Футболизатор | EAN Data Barcode Scanner | PictogramAgenda | Who'sFuckin' | Eversnap - Wedding Snap | Daily Anime News | SnapDish Food Camera | Справочник "Вся Осетия" | nglauber | Twitch | TVShow Time, TV show guide | Hobzy | Stripfilm | Planning Center Services | Facebook Covers - FBCOOLCOVERS | Daybe - 일기가 되는 SNS | BigHippo - Contact Notes Info | Lapse It | My Cloud Player for SoundCloud | 포켓로켓 | ATR | Game Collection Tracker Free, Pro | Quran Cordoba | SoundTracking | LoopLR Social Video | Triple J Unearthed Unofficial | Achievement Hunter | MCS Heritage Fiesta 2013 | Play It | 핫프라이스 - 돈버는 공짜 쇼핑,옥션, 슈팅,프라이스 | soap4all | BoardDrive | Photo Puzzle | REALCITY.cz | Aquarium Manager | 나는 불펜人이다 | SolGroup - Organize groups | SocialWiFi | World Hockey | 팜통 | DoorDresser | Reddit Pics HD | DeviantART Image Gallery | Hír24 | Cosmopolitan | Nők Lapja Café | Pitaco – Bolão que dá prêmios | Tidy - Photo Album | Красная карта | (روزنامه) Rooznameh | Deal.ch | Belle UI Icon Pack, (Donate) | Want it! | Insites - Social Web Feeder | My Achievements | Heritage On The Go | Immobilien Scout24 | Wine-Searcher | Storyteller - Audiobook Player | Tumblr Viewer: tRlbum | スライドショー動画作成♪写真と音楽でおしゃれな動画!めもりぃ | CosmosSync | PhotoCast for Chromecast | Dota Guides | Smart Covers | CityU Apps Lab | uPod light – Podcast player | Tamil Photo Comment | Sinhala Photo Comment | Sanskriti 14 | FILE MANAGER | PIKPIK | Lieferheld - Pizza Pasta Sushi | Delivery Hero - Get Takeaway | Loocator: free sex datings | TweetRoulette | 벨팡-개편 이벤트,컬러링,벨소리,무료,최신가요,링투유 | 벨팡플러스+벨소리,컬러링,링투유,필링,벨링,통화연결음 | 카톡갤러리-카스/카톡/마플/라인/미투 사진저장 | 경주 스탬프투어-현장보고서,스탬프,여행,투어 | AirBuddy | Beautiful Wallpapers HD | Streambels AirPlay/DLNA Player | NearUS | Animals Wallpapers | Shoop! E-Commerce | Force of Me
You can support the project and thank the author for his hard work :)
<a href='https://pledgie.com/campaigns/19144'><img alt='Click here to lend your support to: Universal Image Loader for Android and make a donation at pledgie.com !' src='https://pledgie.com/campaigns/19144.png?skin_name=chrome' border='0' ></a> <a href="http://flattr.com/thing/1110177/nostra13Android-Universal-Image-Loader-on-GitHub" target="_blank"><img src="http://api.flattr.com/button/flattr-badge-large.png" alt="Flattr this" title="Flattr this" border="0" /></a>
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<br /> 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 Tarasevich
Licensed 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.0
Unless required by applicable law or agreed to in writing, software
distributed 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 and
limitations under the License.