SlideShare a Scribd company logo
1 of 31
Download to read offline
Displaying Images
How to manage images nicely
+RobertoOrgiu
@_tiwiz
+MatteoBonifazi
@mbonifazi
Pictures are faster than words
Consider using pictures to explain ideas. They get
people's attention and can be much more efficient than
words.
For media rich applications, BITMAPS are
everywhere.
Handling Bitmaps
Loading bitmaps in app is tricky
● Bitmaps can very easily exhaust an app's memory budget.
● Loading bitmaps on the UI thread can degrade your app's
performance
● If your app is loading multiple bitmaps into memory, you
need to skillfully manage memory and disk caching.
Loading Large Bitmaps Efficiently
Images come in all shapes and sizes. In many
cases they are larger than required for a
typical application user interface (UI).
Read bitmap dimensions and type
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;
The BitmapFactory class provides several
decoding methods (decodeByteArray(),
decodeFile(), decodeResource(), etc.) for
creating a Bitmap from various sources
To avoid java.lang.OutOfMemory
exceptions, check the dimensions of a
bitmap before decoding it.
Load a Scaled Down Version into Memory
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) {
//Downsize of the resources
final int halfHeight = height / 2; final int halfWidth = width / 2;
while ((halfHeight / inSampleSize) >= reqHeight &&
(halfWidth / inSampleSize) >= reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
A power of two value is calculated because
the decoder uses a final value by rounding
down to the nearest power of two, as per
the inSampleSize documentation.
Decode the images
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);
}
If set to true, the decoder will return null (no
bitmap), but the out... fields will still be set,
allowing the caller to query the bitmap without
having to allocate the memory for its pixels.
Load the image into the ImageView
mImageView.setImageBitmap(
decodeSampledBitmapFromResource(getResources(), R.id.myimage, 100, 100));
Caching bitmaps
Load a new bitmap for your apps’ social media
stream, or whatever, but you're out of memory.
Use a Memory Cache
LRU Cache for all of us
This container keeps a list of objects, and ranks them based
upon how many times they’ve been accessed. When it’s
time to evict one of them (to make space for a new object)
the LRUCache already knows which ones to get rid of. All
done without you having to worry about any of it.
Suitable size for a LruCache
Factors should be taken into consideration
● How memory intensive is the rest of your activity and/or
application?
● How many images will be on-screen at once?
● How many need to be available ready to come on-screen?
● What is the screen size and density of the device?
● What dimensions and configuration are the bitmaps?
● How frequently will the images be accessed?
There is no ONE SOLUTION!
Avoid java.lang.OutOfMemory exceptions
Memory LRU cache
private LruCache<String, Bitmap> mMemoryCache;
protected void onCreate(Bundle savedInstanceState) {
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
// Use 1/8th of the available memory for this memory cache.
final int cacheSize = maxMemory / 8;
mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
// The cache size will be measured in kilobytes
// rather than number of items.
return bitmap.getByteCount() / 1024;
}
};
Get max available VM memory,
exceeding this amount will throw an
OutOfMemory exception. Stored in
kilobytes as LruCache takes an
int in its constructor.
Memory LRU cache
// Add bitmap to the cache
public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
if (getBitmapFromMemCache(key) == null) {
mMemoryCache.put(key, bitmap);
}
}
//Retrieve the bitmap from the cache
public Bitmap getBitmapFromMemCache(String key) {
return mMemoryCache.get(key);
}
Disk LRU cache
private DiskLruCache mDiskLruCache;
private static final int DISK_CACHE_SIZE = 1024 * 1024 * 10; // 10MB
protected void onCreate(Bundle savedInstanceState) {
// Initialize disk cache on background thread
File cacheDir = getDiskCacheDir(this, "thumbnails");
new InitDiskCacheTask().execute(cacheDir);
}
class InitDiskCacheTask extends AsyncTask<File, Void, Void> {
protected Void doInBackground(File... params) {
synchronized (mDiskCacheLock) {
File cacheDir = params[0];
mDiskLruCache = DiskLruCache.open(cacheDir, DISK_CACHE_SIZE);
}
....
Disk LRU cache
public void addBitmapToCache(String key, Bitmap bitmap) {
if (getBitmapFromMemCache(key) == null) { // Add to memory cache as before
mMemoryCache.put(key, bitmap);
}
synchronized (mDiskCacheLock) { // Also add to disk cache
if (mDiskLruCache != null && mDiskLruCache.get(key) == null) {
mDiskLruCache.put(key, bitmap);
}
...
public Bitmap getBitmapFromDiskCache(String key) {
synchronized (mDiskCacheLock) {
while (mDiskCacheStarting) {// Wait while disk cache is started
try { mDiskCacheLock.wait(); } ….
if (mDiskLruCache != null) { return mDiskLruCache.get(key); }
....
Disk LRU cache
final String imageKey = String.valueOf(params[0]);
// Check disk cache in background thread
Bitmap bitmap = getBitmapFromDiskCache(imageKey);
if (bitmap == null) { // Not found in disk cache
// Process as normal
final Bitmap bitmap = decodeSampledBitmapFromResource(getResources(),
params[0], 100, 100));
}
// Add final bitmap to caches
addBitmapToCache(imageKey, bitmap);
Going forward
Youtube Video
https://www.youtube.com/watch?v=HY9aaXHx8yA
https://www.youtube.com/watch?v=2TUvmlGoDrw
https://www.youtube.com/watch?v=_ioFW3cyRV0
Reference Link
https://developer.android.com/topic/performance/graphics/index.html
https://developer.android.com/topic/performance/graphics/load-bitmap.html
https://developer.android.com/topic/performance/graphics/manage-memory.html
Can we do it faster?
Yes
We can!
● Picasso
● Glide
Importing the libraries
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.github.bumptech.glide:glide:3.7.0'
Loading the images simply
Picasso.with(context)
.load(urlOfTheImageAsString)
.into(imageView);
Loading the images simply
Picasso.with(context)
.load(R.drawable.ic_image)
.into(imageView);
Loading the images simply
Picasso.with(context)
.load(“file:///android_assets/amazing.png”)
.into(imageView);
Loading the images simply
Picasso.with(context)
.load(new File(...))
.into(imageView);
Managing waiting state and errors
Picasso.with(context)
.load(urlOfTheImageAsString)
.placeholder(R.drawable.placeholder)
.error(R.drawable.error)
.into(imageView);
Advanced features
Picasso.with(context)
.load(url)
.resize(50, 50)
.centerCrop()
.into(imageView)
+MatteoBonifazi
@mbonifazi
Thank You!
+RobertoOrgiu
@_tiwiz

More Related Content

Viewers also liked

Android - Background operation
Android - Background operationAndroid - Background operation
Android - Background operationMatteo Bonifazi
 
Matlab intro
Matlab introMatlab intro
Matlab introfvijayami
 
Matlab for diploma students(1)
Matlab for diploma students(1)Matlab for diploma students(1)
Matlab for diploma students(1)Retheesh Raj
 
Automated histopathological image analysis: a review on ROI extraction
Automated histopathological image analysis: a review on ROI extractionAutomated histopathological image analysis: a review on ROI extraction
Automated histopathological image analysis: a review on ROI extractioniosrjce
 
Summer training in matlab
Summer training in matlabSummer training in matlab
Summer training in matlabArshit Rai
 
Intro matlab and convolution islam
Intro matlab and convolution islamIntro matlab and convolution islam
Intro matlab and convolution islamIslam Alabbasy
 
Digital image processing using matlab (fundamentals)
Digital image processing using matlab (fundamentals)Digital image processing using matlab (fundamentals)
Digital image processing using matlab (fundamentals)Taimur Adil
 
Frequency domain methods
Frequency domain methods Frequency domain methods
Frequency domain methods thanhhoang2012
 
Introduction to Image Processing with MATLAB
Introduction to Image Processing with MATLABIntroduction to Image Processing with MATLAB
Introduction to Image Processing with MATLABSriram Emarose
 
Extraction of region of interest in an image
Extraction of region of interest in an imageExtraction of region of interest in an image
Extraction of region of interest in an imageHarsukh Chandak
 
Spatial filtering using image processing
Spatial filtering using image processingSpatial filtering using image processing
Spatial filtering using image processingAnuj Arora
 
Cours 1 bases de matlab 2eme annees
Cours 1   bases de matlab 2eme anneesCours 1   bases de matlab 2eme annees
Cours 1 bases de matlab 2eme anneesTarik Taleb Bendiab
 
06 spatial filtering DIP
06 spatial filtering DIP06 spatial filtering DIP
06 spatial filtering DIPbabak danyal
 

Viewers also liked (20)

Android - Saving data
Android - Saving dataAndroid - Saving data
Android - Saving data
 
Android things intro
Android things introAndroid things intro
Android things intro
 
Android - Background operation
Android - Background operationAndroid - Background operation
Android - Background operation
 
Matlab intro
Matlab introMatlab intro
Matlab intro
 
Matlab for diploma students(1)
Matlab for diploma students(1)Matlab for diploma students(1)
Matlab for diploma students(1)
 
Automated histopathological image analysis: a review on ROI extraction
Automated histopathological image analysis: a review on ROI extractionAutomated histopathological image analysis: a review on ROI extraction
Automated histopathological image analysis: a review on ROI extraction
 
Intro to matlab
Intro to matlabIntro to matlab
Intro to matlab
 
Summer training in matlab
Summer training in matlabSummer training in matlab
Summer training in matlab
 
Intro matlab and convolution islam
Intro matlab and convolution islamIntro matlab and convolution islam
Intro matlab and convolution islam
 
Image Processing Using MATLAB
Image Processing Using MATLABImage Processing Using MATLAB
Image Processing Using MATLAB
 
Digital image processing using matlab (fundamentals)
Digital image processing using matlab (fundamentals)Digital image processing using matlab (fundamentals)
Digital image processing using matlab (fundamentals)
 
Frequency domain methods
Frequency domain methods Frequency domain methods
Frequency domain methods
 
Introduction to Image Processing with MATLAB
Introduction to Image Processing with MATLABIntroduction to Image Processing with MATLAB
Introduction to Image Processing with MATLAB
 
Spatial domain and filtering
Spatial domain and filteringSpatial domain and filtering
Spatial domain and filtering
 
IMAGE PROCESSING
IMAGE PROCESSINGIMAGE PROCESSING
IMAGE PROCESSING
 
Extraction of region of interest in an image
Extraction of region of interest in an imageExtraction of region of interest in an image
Extraction of region of interest in an image
 
Region Of Interest Extraction
Region Of Interest ExtractionRegion Of Interest Extraction
Region Of Interest Extraction
 
Spatial filtering using image processing
Spatial filtering using image processingSpatial filtering using image processing
Spatial filtering using image processing
 
Cours 1 bases de matlab 2eme annees
Cours 1   bases de matlab 2eme anneesCours 1   bases de matlab 2eme annees
Cours 1 bases de matlab 2eme annees
 
06 spatial filtering DIP
06 spatial filtering DIP06 spatial filtering DIP
06 spatial filtering DIP
 

Similar to Android - Displaying images

カメラアプリ実装のコツ
カメラアプリ実装のコツカメラアプリ実装のコツ
カメラアプリ実装のコツtac0x2a
 
Android memory and performance optimization
Android memory and performance optimizationAndroid memory and performance optimization
Android memory and performance optimizationveeracynixit
 
Android memory and performance optimization
Android memory and performance optimizationAndroid memory and performance optimization
Android memory and performance optimizationveeracynixit
 
Android memory and performance optimization
Android memory and performance optimizationAndroid memory and performance optimization
Android memory and performance optimizationveeracynixit
 
Android UI Tips & Tricks
Android UI Tips & TricksAndroid UI Tips & Tricks
Android UI Tips & TricksDroidConTLV
 
Android ui tips & tricks
Android ui tips & tricksAndroid ui tips & tricks
Android ui tips & tricksShem Magnezi
 
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficientTh 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficientBin Shao
 
XebiCon'17 : Faites chauffer les neurones de votre Smartphone avec du Deep Le...
XebiCon'17 : Faites chauffer les neurones de votre Smartphone avec du Deep Le...XebiCon'17 : Faites chauffer les neurones de votre Smartphone avec du Deep Le...
XebiCon'17 : Faites chauffer les neurones de votre Smartphone avec du Deep Le...Publicis Sapient Engineering
 
Stupid Canvas Tricks
Stupid Canvas TricksStupid Canvas Tricks
Stupid Canvas Tricksdeanhudson
 
Kotlin Mullets
Kotlin MulletsKotlin Mullets
Kotlin MulletsJames Ward
 
Reversible data hiding in encrypted images by reserving room before encryption
Reversible data hiding in encrypted images by reserving room before encryptionReversible data hiding in encrypted images by reserving room before encryption
Reversible data hiding in encrypted images by reserving room before encryptionIEEEFINALYEARPROJECTS
 
3 track kinect@Bicocca - sdk e camere
3   track kinect@Bicocca - sdk e camere3   track kinect@Bicocca - sdk e camere
3 track kinect@Bicocca - sdk e camereMatteo Valoriani
 
Android programming -_pushing_the_limits
Android programming -_pushing_the_limitsAndroid programming -_pushing_the_limits
Android programming -_pushing_the_limitsDroidcon Berlin
 
426 lecture 4: AR Developer Tools
426 lecture 4: AR Developer Tools426 lecture 4: AR Developer Tools
426 lecture 4: AR Developer ToolsMark Billinghurst
 
Android Support Library
Android Support LibraryAndroid Support Library
Android Support LibraryAlexey Ustenko
 

Similar to Android - Displaying images (20)

Bitmap management like a boss
Bitmap management like a bossBitmap management like a boss
Bitmap management like a boss
 
カメラアプリ実装のコツ
カメラアプリ実装のコツカメラアプリ実装のコツ
カメラアプリ実装のコツ
 
Work With Images
Work With ImagesWork With Images
Work With Images
 
Android memory and performance optimization
Android memory and performance optimizationAndroid memory and performance optimization
Android memory and performance optimization
 
Android memory and performance optimization
Android memory and performance optimizationAndroid memory and performance optimization
Android memory and performance optimization
 
Android memory and performance optimization
Android memory and performance optimizationAndroid memory and performance optimization
Android memory and performance optimization
 
Android UI Tips & Tricks
Android UI Tips & TricksAndroid UI Tips & Tricks
Android UI Tips & Tricks
 
Android ui tips & tricks
Android ui tips & tricksAndroid ui tips & tricks
Android ui tips & tricks
 
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficientTh 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
 
Android workshop
Android workshopAndroid workshop
Android workshop
 
XebiCon'17 : Faites chauffer les neurones de votre Smartphone avec du Deep Le...
XebiCon'17 : Faites chauffer les neurones de votre Smartphone avec du Deep Le...XebiCon'17 : Faites chauffer les neurones de votre Smartphone avec du Deep Le...
XebiCon'17 : Faites chauffer les neurones de votre Smartphone avec du Deep Le...
 
Stupid Canvas Tricks
Stupid Canvas TricksStupid Canvas Tricks
Stupid Canvas Tricks
 
Kotlin Mullets
Kotlin MulletsKotlin Mullets
Kotlin Mullets
 
Reversible data hiding in encrypted images by reserving room before encryption
Reversible data hiding in encrypted images by reserving room before encryptionReversible data hiding in encrypted images by reserving room before encryption
Reversible data hiding in encrypted images by reserving room before encryption
 
3 track kinect@Bicocca - sdk e camere
3   track kinect@Bicocca - sdk e camere3   track kinect@Bicocca - sdk e camere
3 track kinect@Bicocca - sdk e camere
 
Java Programming Projects
Java Programming ProjectsJava Programming Projects
Java Programming Projects
 
Android programming -_pushing_the_limits
Android programming -_pushing_the_limitsAndroid programming -_pushing_the_limits
Android programming -_pushing_the_limits
 
426 lecture 4: AR Developer Tools
426 lecture 4: AR Developer Tools426 lecture 4: AR Developer Tools
426 lecture 4: AR Developer Tools
 
Android Support Library
Android Support LibraryAndroid Support Library
Android Support Library
 
Windows Phone Launchers and Choosers
Windows Phone Launchers and ChoosersWindows Phone Launchers and Choosers
Windows Phone Launchers and Choosers
 

More from Matteo Bonifazi

Invading the home screen
Invading the home screenInvading the home screen
Invading the home screenMatteo Bonifazi
 
Engage user with actions
Engage user with actionsEngage user with actions
Engage user with actionsMatteo Bonifazi
 
Kotlin killed Java stars
Kotlin killed Java starsKotlin killed Java stars
Kotlin killed Java starsMatteo Bonifazi
 
Firebase-ized your mobile app
Firebase-ized  your mobile appFirebase-ized  your mobile app
Firebase-ized your mobile appMatteo Bonifazi
 
The Firebase tier for your mobile app - DevFest CH
The Firebase tier for your mobile app - DevFest CHThe Firebase tier for your mobile app - DevFest CH
The Firebase tier for your mobile app - DevFest CHMatteo Bonifazi
 
Engage and retain users in the android world - Droidcon Italy 2016
Engage and retain users in the android world - Droidcon Italy 2016Engage and retain users in the android world - Droidcon Italy 2016
Engage and retain users in the android world - Droidcon Italy 2016Matteo Bonifazi
 
UaMobitech - App Links and App Indexing API
UaMobitech - App Links and App Indexing APIUaMobitech - App Links and App Indexing API
UaMobitech - App Links and App Indexing APIMatteo Bonifazi
 
The unconventional devices for the Android video streaming
The unconventional devices for the Android video streamingThe unconventional devices for the Android video streaming
The unconventional devices for the Android video streamingMatteo Bonifazi
 
Google IO - Five months later
Google IO - Five months laterGoogle IO - Five months later
Google IO - Five months laterMatteo Bonifazi
 
Video Streaming: from the native Android player to uncoventional devices
Video Streaming: from the native Android player to uncoventional devicesVideo Streaming: from the native Android player to uncoventional devices
Video Streaming: from the native Android player to uncoventional devicesMatteo Bonifazi
 

More from Matteo Bonifazi (13)

Invading the home screen
Invading the home screenInvading the home screen
Invading the home screen
 
Engage user with actions
Engage user with actionsEngage user with actions
Engage user with actions
 
Kotlin killed Java stars
Kotlin killed Java starsKotlin killed Java stars
Kotlin killed Java stars
 
Android JET Navigation
Android JET NavigationAndroid JET Navigation
Android JET Navigation
 
Firebase-ized your mobile app
Firebase-ized  your mobile appFirebase-ized  your mobile app
Firebase-ized your mobile app
 
Backendless apps
Backendless appsBackendless apps
Backendless apps
 
The Firebase tier for your mobile app - DevFest CH
The Firebase tier for your mobile app - DevFest CHThe Firebase tier for your mobile app - DevFest CH
The Firebase tier for your mobile app - DevFest CH
 
Engage and retain users in the android world - Droidcon Italy 2016
Engage and retain users in the android world - Droidcon Italy 2016Engage and retain users in the android world - Droidcon Italy 2016
Engage and retain users in the android world - Droidcon Italy 2016
 
UaMobitech - App Links and App Indexing API
UaMobitech - App Links and App Indexing APIUaMobitech - App Links and App Indexing API
UaMobitech - App Links and App Indexing API
 
The unconventional devices for the Android video streaming
The unconventional devices for the Android video streamingThe unconventional devices for the Android video streaming
The unconventional devices for the Android video streaming
 
Google IO - Five months later
Google IO - Five months laterGoogle IO - Five months later
Google IO - Five months later
 
Video Streaming: from the native Android player to uncoventional devices
Video Streaming: from the native Android player to uncoventional devicesVideo Streaming: from the native Android player to uncoventional devices
Video Streaming: from the native Android player to uncoventional devices
 
Enlarge your screen
Enlarge your screenEnlarge your screen
Enlarge your screen
 

Recently uploaded

Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost LoverPowerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost LoverPsychicRuben LoveSpells
 
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun serviceCALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun serviceanilsa9823
 
哪里有卖的《俄亥俄大学学历证书+俄亥俄大学文凭证书+俄亥俄大学学位证书》Q微信741003700《俄亥俄大学学位证书复制》办理俄亥俄大学毕业证成绩单|购买...
哪里有卖的《俄亥俄大学学历证书+俄亥俄大学文凭证书+俄亥俄大学学位证书》Q微信741003700《俄亥俄大学学位证书复制》办理俄亥俄大学毕业证成绩单|购买...哪里有卖的《俄亥俄大学学历证书+俄亥俄大学文凭证书+俄亥俄大学学位证书》Q微信741003700《俄亥俄大学学位证书复制》办理俄亥俄大学毕业证成绩单|购买...
哪里有卖的《俄亥俄大学学历证书+俄亥俄大学文凭证书+俄亥俄大学学位证书》Q微信741003700《俄亥俄大学学位证书复制》办理俄亥俄大学毕业证成绩单|购买...wyqazy
 
9892124323 | Book Call Girls in Juhu and escort services 24x7
9892124323 | Book Call Girls in Juhu and escort services 24x79892124323 | Book Call Girls in Juhu and escort services 24x7
9892124323 | Book Call Girls in Juhu and escort services 24x7Pooja Nehwal
 
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort ServiceBDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort ServiceDelhi Call girls
 
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,Pooja Nehwal
 
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCRFULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCRnishacall1
 
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual serviceCALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual serviceanilsa9823
 
Chandigarh Call Girls Service ❤️🍑 9115573837 👄🫦Independent Escort Service Cha...
Chandigarh Call Girls Service ❤️🍑 9115573837 👄🫦Independent Escort Service Cha...Chandigarh Call Girls Service ❤️🍑 9115573837 👄🫦Independent Escort Service Cha...
Chandigarh Call Girls Service ❤️🍑 9115573837 👄🫦Independent Escort Service Cha...Niamh verma
 

Recently uploaded (9)

Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost LoverPowerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
 
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun serviceCALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
 
哪里有卖的《俄亥俄大学学历证书+俄亥俄大学文凭证书+俄亥俄大学学位证书》Q微信741003700《俄亥俄大学学位证书复制》办理俄亥俄大学毕业证成绩单|购买...
哪里有卖的《俄亥俄大学学历证书+俄亥俄大学文凭证书+俄亥俄大学学位证书》Q微信741003700《俄亥俄大学学位证书复制》办理俄亥俄大学毕业证成绩单|购买...哪里有卖的《俄亥俄大学学历证书+俄亥俄大学文凭证书+俄亥俄大学学位证书》Q微信741003700《俄亥俄大学学位证书复制》办理俄亥俄大学毕业证成绩单|购买...
哪里有卖的《俄亥俄大学学历证书+俄亥俄大学文凭证书+俄亥俄大学学位证书》Q微信741003700《俄亥俄大学学位证书复制》办理俄亥俄大学毕业证成绩单|购买...
 
9892124323 | Book Call Girls in Juhu and escort services 24x7
9892124323 | Book Call Girls in Juhu and escort services 24x79892124323 | Book Call Girls in Juhu and escort services 24x7
9892124323 | Book Call Girls in Juhu and escort services 24x7
 
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort ServiceBDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
 
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
 
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCRFULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
 
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual serviceCALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
 
Chandigarh Call Girls Service ❤️🍑 9115573837 👄🫦Independent Escort Service Cha...
Chandigarh Call Girls Service ❤️🍑 9115573837 👄🫦Independent Escort Service Cha...Chandigarh Call Girls Service ❤️🍑 9115573837 👄🫦Independent Escort Service Cha...
Chandigarh Call Girls Service ❤️🍑 9115573837 👄🫦Independent Escort Service Cha...
 

Android - Displaying images

  • 1. Displaying Images How to manage images nicely +RobertoOrgiu @_tiwiz +MatteoBonifazi @mbonifazi
  • 2. Pictures are faster than words Consider using pictures to explain ideas. They get people's attention and can be much more efficient than words.
  • 3. For media rich applications, BITMAPS are everywhere.
  • 4. Handling Bitmaps Loading bitmaps in app is tricky ● Bitmaps can very easily exhaust an app's memory budget. ● Loading bitmaps on the UI thread can degrade your app's performance ● If your app is loading multiple bitmaps into memory, you need to skillfully manage memory and disk caching.
  • 5. Loading Large Bitmaps Efficiently
  • 6. Images come in all shapes and sizes. In many cases they are larger than required for a typical application user interface (UI).
  • 7. Read bitmap dimensions and type 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; The BitmapFactory class provides several decoding methods (decodeByteArray(), decodeFile(), decodeResource(), etc.) for creating a Bitmap from various sources To avoid java.lang.OutOfMemory exceptions, check the dimensions of a bitmap before decoding it.
  • 8. Load a Scaled Down Version into Memory 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) { //Downsize of the resources final int halfHeight = height / 2; final int halfWidth = width / 2; while ((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth) { inSampleSize *= 2; } } return inSampleSize; } A power of two value is calculated because the decoder uses a final value by rounding down to the nearest power of two, as per the inSampleSize documentation.
  • 9. Decode the images 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); } If set to true, the decoder will return null (no bitmap), but the out... fields will still be set, allowing the caller to query the bitmap without having to allocate the memory for its pixels.
  • 10. Load the image into the ImageView mImageView.setImageBitmap( decodeSampledBitmapFromResource(getResources(), R.id.myimage, 100, 100));
  • 12. Load a new bitmap for your apps’ social media stream, or whatever, but you're out of memory.
  • 13. Use a Memory Cache LRU Cache for all of us This container keeps a list of objects, and ranks them based upon how many times they’ve been accessed. When it’s time to evict one of them (to make space for a new object) the LRUCache already knows which ones to get rid of. All done without you having to worry about any of it.
  • 14. Suitable size for a LruCache Factors should be taken into consideration ● How memory intensive is the rest of your activity and/or application? ● How many images will be on-screen at once? ● How many need to be available ready to come on-screen? ● What is the screen size and density of the device? ● What dimensions and configuration are the bitmaps? ● How frequently will the images be accessed?
  • 15. There is no ONE SOLUTION! Avoid java.lang.OutOfMemory exceptions
  • 16. Memory LRU cache private LruCache<String, Bitmap> mMemoryCache; protected void onCreate(Bundle savedInstanceState) { final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); // Use 1/8th of the available memory for this memory cache. final int cacheSize = maxMemory / 8; mMemoryCache = new LruCache<String, Bitmap>(cacheSize) { @Override protected int sizeOf(String key, Bitmap bitmap) { // The cache size will be measured in kilobytes // rather than number of items. return bitmap.getByteCount() / 1024; } }; Get max available VM memory, exceeding this amount will throw an OutOfMemory exception. Stored in kilobytes as LruCache takes an int in its constructor.
  • 17. Memory LRU cache // Add bitmap to the cache public void addBitmapToMemoryCache(String key, Bitmap bitmap) { if (getBitmapFromMemCache(key) == null) { mMemoryCache.put(key, bitmap); } } //Retrieve the bitmap from the cache public Bitmap getBitmapFromMemCache(String key) { return mMemoryCache.get(key); }
  • 18. Disk LRU cache private DiskLruCache mDiskLruCache; private static final int DISK_CACHE_SIZE = 1024 * 1024 * 10; // 10MB protected void onCreate(Bundle savedInstanceState) { // Initialize disk cache on background thread File cacheDir = getDiskCacheDir(this, "thumbnails"); new InitDiskCacheTask().execute(cacheDir); } class InitDiskCacheTask extends AsyncTask<File, Void, Void> { protected Void doInBackground(File... params) { synchronized (mDiskCacheLock) { File cacheDir = params[0]; mDiskLruCache = DiskLruCache.open(cacheDir, DISK_CACHE_SIZE); } ....
  • 19. Disk LRU cache public void addBitmapToCache(String key, Bitmap bitmap) { if (getBitmapFromMemCache(key) == null) { // Add to memory cache as before mMemoryCache.put(key, bitmap); } synchronized (mDiskCacheLock) { // Also add to disk cache if (mDiskLruCache != null && mDiskLruCache.get(key) == null) { mDiskLruCache.put(key, bitmap); } ... public Bitmap getBitmapFromDiskCache(String key) { synchronized (mDiskCacheLock) { while (mDiskCacheStarting) {// Wait while disk cache is started try { mDiskCacheLock.wait(); } …. if (mDiskLruCache != null) { return mDiskLruCache.get(key); } ....
  • 20. Disk LRU cache final String imageKey = String.valueOf(params[0]); // Check disk cache in background thread Bitmap bitmap = getBitmapFromDiskCache(imageKey); if (bitmap == null) { // Not found in disk cache // Process as normal final Bitmap bitmap = decodeSampledBitmapFromResource(getResources(), params[0], 100, 100)); } // Add final bitmap to caches addBitmapToCache(imageKey, bitmap);
  • 21. Going forward Youtube Video https://www.youtube.com/watch?v=HY9aaXHx8yA https://www.youtube.com/watch?v=2TUvmlGoDrw https://www.youtube.com/watch?v=_ioFW3cyRV0 Reference Link https://developer.android.com/topic/performance/graphics/index.html https://developer.android.com/topic/performance/graphics/load-bitmap.html https://developer.android.com/topic/performance/graphics/manage-memory.html
  • 22. Can we do it faster?
  • 24. Importing the libraries compile 'com.squareup.picasso:picasso:2.5.2' compile 'com.github.bumptech.glide:glide:3.7.0'
  • 25. Loading the images simply Picasso.with(context) .load(urlOfTheImageAsString) .into(imageView);
  • 26. Loading the images simply Picasso.with(context) .load(R.drawable.ic_image) .into(imageView);
  • 27. Loading the images simply Picasso.with(context) .load(“file:///android_assets/amazing.png”) .into(imageView);
  • 28. Loading the images simply Picasso.with(context) .load(new File(...)) .into(imageView);
  • 29. Managing waiting state and errors Picasso.with(context) .load(urlOfTheImageAsString) .placeholder(R.drawable.placeholder) .error(R.drawable.error) .into(imageView);