SlideShare a Scribd company logo
1 of 81
WORKING WITH Images
Sergey Tarasevich
@nostra13
Who’s this man?
Sergey Tarasevich (@nostra13)
• Android developer at CactusSoft
• Author of «Universal Image Loader» library
• Certified Java SE 7 Programmer
Agenda
1. Images in Android
2. ImageView widget
3. Image as Bitmap
4. Android Bitmap API
5. Displaying Bitmaps Efficiently
6. Issues & Solutions
Bonus:
Make own Open Source project popular
Supported formats
Format Encoder Decoder
JPEG + +
GIF +
PNG + +
BMP +
WebP + (Android 4.0+)
(Lossless, Transparency,
Android 4.2.1+)
+ (Android 4.0+)
(Lossless, Transparency,
Android 4.2.1+)
Image sources
• Resources
– drawables
– assets
• Local files (file system/SD card)
• Remote
• …
Widget
<ImageView
android:id="@+id/test_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/test" />
ImageView
• void setImageBitmap(Bitmap bm)
• void setImageDrawable(Drawable drawable)
• void setImageResource(int resId)
• void setImageURI(Uri uri)
ImageView params
• android:baseline
• android:baselineAlignBottom
• android:adjustViewBounds
• android:cropToPadding
• android:maxHeight
• android:maxWidth
• android:scaleType
• android:src
• android:tint
• android:tintMode
ImageView scaleType test
Sample Layout #1
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/cat« />
Scale Type: fitCenter
Scale Type: fitStart
Scale Type: fitEnd
Scale Type: fitXY
Scale Type: matrix
Scale Type: center
Scale Type: centerCrop
Scale Type: centerInside
Sample Layout #2
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_gravity="center"
android:src="@drawable/cat"
android:background=“@color/gray“ />
</FrameLayout>
Scale Type: fitCenter
Scale Type: fitStart
Scale Type: fitEnd
Scale Type: fitXY
Scale Type: matrix
Scale Type: center
Scale Type: centerCrop
Scale Type: centerInside
Sample Layout #3
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="@drawable/cat"
android:background=“@color/gray“ />
</FrameLayout>
Scale Type: center
"false" = android:adjustViewBounds = "true"
?
1 2 3
- ?
Scale Type: center
"false" = android:adjustViewBounds = "true"
Scale Type: centerCrop
"false" = android:adjustViewBounds = "true"
?
1 2 3
- ?
Scale Type: centerCrop
"false" = android:adjustViewBounds = "true"
Scale Type: centerInside
"false" = android:adjustViewBounds = "true"
Scale Type: fitXY
"false" = android:adjustViewBounds = "true"
?
1 2 3
- ?
Scale Type: fitXY
"false" = android:adjustViewBounds = "true"
Scale Type: fitCenter
"false" = android:adjustViewBounds = "true"
Scale Type: fitStart
"false" = android:adjustViewBounds = "true"
Scale Type: fitEnd
"false" = android:adjustViewBounds = "true"
Scale Type: matrix
"false" = android:adjustViewBounds = "true"
ImageView inside
…
public void setAdjustViewBounds(boolean
adjustViewBounds) {
mAdjustViewBounds = adjustViewBounds;
if (adjustViewBounds) {
setScaleType(ScaleType.FIT_CENTER);
}
}
…
ImageView padding?
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/cat"
android:scaleType="centerCrop"
android:padding="20dp" />
ImageView padding
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/cat"
android:scaleType="centerCrop"
android:padding="20dp"
android:cropToPadding="true"/>
ImageView surprises
1. ImageView.setAdjustViewBounds(boolean)
– triggers ImageView.setScaleType(ScaleType.FIT_CENTER)
2. ImageView.setImageMatrix(Matrix)
– works for ScaleType.MATRIX
– doesn’t work for ScaleType.FIT_XY
– work partially for other ScaleTypes
3. android:maxWidth & android:maxHeight
– works only if android:adjustViewBounds="true“
4. android:padding
– works “strangely” for ScaleType.CENTER|CENTER_CROP|MATRIX
without android:cropToPadding="true"
Image as Bitmap
Image as Bitmap
Image in memory
=
Bitmap
=
pixel data
Bitmap in memory
• On Android 2.3.3 and lower (<= API level 10)
Bitmap =
Heap Native memory
Bitmap object Pixel data
Heap
Bitmap object + Pixel data
• On Android 3.0 and above (>= API level 11)
Bitmap =
Bitmap in memory
• On Android 2.3.3 and lower (<= API level 10)
Bitmap =
Heap Native memory
Bitmap object Pixel data
Garbage Collector
Bitmap.recycle()
Bitmap in memory
• On Android 2.3.3 and lower (<= API level 10)
Bitmap =
Heap Native memory
Bitmap object Pixel data
Heap
Bitmap object + Pixel data
• On Android 3.0 and above (>= API level 11)
Bitmap =
Garbage Collector
Bitmap Pixel Configuration
Bitmap.Config:
– ALPHA_8
• 1 pixel = 1 byte = [AAAAAAAA]
– RGB_565
• 1 pixel = 2 bytes = [RRRRRGGG GGGBBBBB]
– ARGB_4444
• 1 pixel = 2 bytes = [AAAARRRR GGGGBBBB]
– ARGB_8888
• 1 pixel = 4 bytes =
[AAAAAAAA RRRRRRRR GGGGGGGG BBBBBBBB]
Bitmap API
Bitmap Inside
• long mNativeBitmap
• int mWidth
• int mHeight
• int mDensity
• boolean mIsMutable
• boolean mRecycled
• boolean mRequestPremultiplied
Bitmap Outside
• Bitmap createBitmap(int width, int height,
Config config)
• Bitmap createBitmap(int colors[], int width,
int height, Config config)
• Bitmap createBitmap(Bitmap source, int x, int y,
int width, int height, Matrix m, boolean filter)
• Bitmap createScaledBitmap(Bitmap source,
int dstWidth, int dstHeight, boolean filter)
BitmapFactory
• Bitmap decodeStream(InputStream is,
BitmapFactory.Options opts)
• Bitmap decodeFile(String path,
BitmapFactory.Options opts)
• Bitmap decodeByteArray(byte[] data,
BitmapFactory.Options opts)
• Bitmap decodeResource(Resources res, int resId,
BitmapFactory.Options opts)
• Bitmap decodeFileDescriptor(FileDescriptor fd,
BitmapFactory.Options opts)
BitmapFactory
• Bitmap decodeStream(InputStream is,
BitmapFactory.Options opts)
BitmapFactory.Options
in*
in*
in*
out*
out*
out*
BitmapFactory.Options
API 1
• inJustDecodeBounds
• outWidth
• outHeight
• outMimeType
• inDither
• inPreferredConfig
• inSampleSize
• inTempStorage
= [true | false]
= int
= int
= String
= [true | false]
= Bitmap.Config [ARGB_8888]
= int
= byte[] [16Kb]
BitmapFactory.Options
API 4
• inDensity
• inTargetDensity
• inScreenDensity
• inScaled
• inInputShareable
• inPurgeable
= [0]
= [0]
= [0]
= [true | false]
= [true | false]
= [true | false]
BitmapFactory.Options
API 10
• inPreferQualityOverSpeed = [true | false]
API 11
• inBitmap = Bitmap
• inMutable = [true | false]
API 19
• inPremultiplied = [true | false]
[Alpha, R-Color, G-Color, B-Color]
Color = Color * Alpha / 255
E.g.: [128, 255, 0, 0] -> [128, 128, 0, 0]
[32, 255, 100, 32] -> [32, 32, 12, 4]
BitmapFactory.Options.inBitmap
Allow to reuse incoming Bitmap object
• Bitmap must be mutable
• If Bitmap can’t be reused ->
IllegalArgumentException
• Reused Bitmap shouldn’t be used
afterwards
BitmapFactory.Options.inBitmap
Prior KITKAT (< API 19):
– decoded image must be JPG or PNG
– Config of reused Bitmap will override
inPrefferedConfig
– decoded bitmap size == reused bitmap size
As of KITKAT (>= API 19):
– decoded bitmap byte count <= reused
bitmap byte count
BitmapRegionDecoder
BitmapRegionDecoder.newInstance(
InputStream is, boolean isShareable)
• Bitmap decodeRegion(Rect rect,
BitmapFactory.Options options)
Bitmap
boolean compress(CompressFormat format,
int quality, OutputStream stream)
enum CompressFormat
• JPEG
• PNG
• WEBP
Displaying Bitmaps Efficiently
Load & Display Bitmap
• Read bitmap dimensions and type
• Load a scaled down version into memory
– process bitmaps off the UI thread
• Use memory cache & disk cache
– handle configuration changes
• Manage bitmap memory
– on Android 2.3.3 and lower
– on Android 3.0 and higher
Read dimensions and type
BitmapFactory.Options opts =
new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeStream(stream, opts);
int imageWidth = opts.outWidth;
int imageHeight = opts.outHeight;
String imageType = opts.outMimeType;
Decode subsampled bitmap
BitmapFactory.Options opts =
new BitmapFactory.Options();
opts.inSampleSize =
calculateInSampleSize(imageWidth, imageHeight,
destWidth, destHeight);
…
Bitmap bmp =
BitmapFactory.decodeStream(stream, opts);
Memory Cache
• LruCache
– SoftReference and WeakReference are not
recommended since Android 2.3 (API 9)
• Cache size depends on:
– How memory intensive is the rest of your app?
– How many images will be on-screen at once?
– What is the screen size and density of the device?
– What dimensions and config are the bitmaps?
– How frequently will the images be accessed?
– Can you balance quality against quantity?
Disk cache
Save images before caching in memory
and/or
Save bitmaps after caching in memory
Manage memory (< API 11)
• Use Bitmap.recycle()
(only if bitmap is no longer being used)
• Count references of displayed and cached
bitmaps
• Recycle bitmap only if:
– mDisplayRefCount == 0 && mCacheRefCount == 0
– Bitmap.isRecycled() == false
Manage memory (>= API 11)
• Use BitmapFactory.Options.inBitmap
(only if bitmap is no longer being used)
LruCache<String, Bitmap> mMemoryCache;
Set<SoftReference<Bitmap>> mReusableBitmaps;
Issues & Solutions
Issue #1
Bitmap bmp = BitmapFactory.decodeFile(imagePath);
...
imageView.setImageBitmap(bmp);
“Bitmap too large to be uploaded into a
texture (2592x1944, max=2048x2048)”
Solution #1
“Bitmap too large to be uploaded into a
texture (2592x1944, max=2048x2048)”
int[] maxTextureSize = new int[1];
GLES10.glGetIntegerv(GL10.GL_MAX_TEXTURE_SIZE,
maxTextureSize, 0);
int maxBitmapDimension = maxTextureSize[0]; // 2048
Issue #2
Bitmap scaledBmp =
Bitmap.createScaledBitmap(originalBmp, ...);
originalBmp.recycle();
imageView.setImageBitmap(scaledBmp);
“java.lang.RuntimeException:
Canvas: trying to use a recycled bitmap…”
Solution #2
“java.lang.RuntimeException:
Canvas: trying to use a recycled bitmap…”
Bitmap scaledBmp =
Bitmap.createScaledBitmap(originalBmp, ...);
if (scaledBmp != originalBmp) {
originalBmp.recycle();
}
imageView.setImageBitmap(scaledBmp);
Issue #3
Bitmap bmp = BitmapFactory.decodeStream(stream);
“--- SkImageDecoder::Factory returned null”
Solution #3
Check if:
• Stream is not an image (e.g. HTML page)
• Stream is not reset
• Image format or compression isn’t
supported (some JPEGs, WebP on Android
<4.0)
Bonus
Make own Open Source project
popular
On Start
• Readme design
– Beautiful image
– Quick setup
– Structured info about usage
• Sample project
• Quick responses on issues
On Resume
• Documentation
– Java docs
– Wiki
• Keep project alive (often commits,
continuous refactoring)
• Mavenization
• Don’t rely on contributions
Thanks!
Questions?

More Related Content

What's hot

파이썬 프로퍼티 디스크립터 이해하기
파이썬 프로퍼티 디스크립터 이해하기파이썬 프로퍼티 디스크립터 이해하기
파이썬 프로퍼티 디스크립터 이해하기Yong Joon Moon
 
RAPID - Building a highly usable API Design language with XText
RAPID - Building a highly usable API Design language with XTextRAPID - Building a highly usable API Design language with XText
RAPID - Building a highly usable API Design language with XTextTed Epstein
 
Unity で実装するエイジングテストのお話
Unity で実装するエイジングテストのお話Unity で実装するエイジングテストのお話
Unity で実装するエイジングテストのお話Shota Baba
 
iPhoneでリアルタイムマルチプレイを実現!Photon Network Engine
iPhoneでリアルタイムマルチプレイを実現!Photon Network EngineiPhoneでリアルタイムマルチプレイを実現!Photon Network Engine
iPhoneでリアルタイムマルチプレイを実現!Photon Network EngineGMO GlobalSign Holdings K.K.
 
Test-Driven Development of Xtext DSLs
Test-Driven Development  of Xtext DSLsTest-Driven Development  of Xtext DSLs
Test-Driven Development of Xtext DSLsmeysholdt
 
GDC Europe 2014: Unreal Engine 4 for Programmers - Lessons Learned & Things t...
GDC Europe 2014: Unreal Engine 4 for Programmers - Lessons Learned & Things t...GDC Europe 2014: Unreal Engine 4 for Programmers - Lessons Learned & Things t...
GDC Europe 2014: Unreal Engine 4 for Programmers - Lessons Learned & Things t...Gerke Max Preussner
 
ビジュアルスクリプティング (旧:Bolt) で始めるUnity入門3日目 ゲームをカスタマイズしよう
ビジュアルスクリプティング (旧:Bolt) で始めるUnity入門3日目 ゲームをカスタマイズしようビジュアルスクリプティング (旧:Bolt) で始めるUnity入門3日目 ゲームをカスタマイズしよう
ビジュアルスクリプティング (旧:Bolt) で始めるUnity入門3日目 ゲームをカスタマイズしようUnity Technologies Japan K.K.
 
Jenkins 2を使った究極のpipeline ~ 明日もう一度来てください、本物のpipelineをお見せしますよ ~
Jenkins 2を使った究極のpipeline ~ 明日もう一度来てください、本物のpipelineをお見せしますよ ~Jenkins 2を使った究極のpipeline ~ 明日もう一度来てください、本物のpipelineをお見せしますよ ~
Jenkins 2を使った究極のpipeline ~ 明日もう一度来てください、本物のpipelineをお見せしますよ ~ikikko
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytestHector Canto
 
はじめてのUnreal Engine 4
はじめてのUnreal Engine 4はじめてのUnreal Engine 4
はじめてのUnreal Engine 4Shun Sasaki
 
[143] Modern C++ 무조건 써야 해?
[143] Modern C++ 무조건 써야 해?[143] Modern C++ 무조건 써야 해?
[143] Modern C++ 무조건 써야 해?NAVER D2
 
How we optimized our Game - Jake & Tess' Finding Monsters Adventure
How we optimized our Game - Jake & Tess' Finding Monsters AdventureHow we optimized our Game - Jake & Tess' Finding Monsters Adventure
How we optimized our Game - Jake & Tess' Finding Monsters AdventureFelipe Lira
 
Unity Roadmap 2020: Core Engine & Creator Tools
Unity Roadmap 2020: Core Engine & Creator ToolsUnity Roadmap 2020: Core Engine & Creator Tools
Unity Roadmap 2020: Core Engine & Creator ToolsUnity Technologies
 
Py.test
Py.testPy.test
Py.testsoasme
 
Unity 2018-2019を見据えたDeNAのUnity開発のこれから [DeNA TechCon 2019]
Unity 2018-2019を見据えたDeNAのUnity開発のこれから [DeNA TechCon 2019]Unity 2018-2019を見据えたDeNAのUnity開発のこれから [DeNA TechCon 2019]
Unity 2018-2019を見据えたDeNAのUnity開発のこれから [DeNA TechCon 2019]DeNA
 
Android Multimedia Framework
Android Multimedia FrameworkAndroid Multimedia Framework
Android Multimedia FrameworkPicker Weng
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsYura Nosenko
 

What's hot (20)

UE4における自動プレイのポストモーテム
UE4における自動プレイのポストモーテム  UE4における自動プレイのポストモーテム
UE4における自動プレイのポストモーテム
 
Android Internals
Android InternalsAndroid Internals
Android Internals
 
파이썬 프로퍼티 디스크립터 이해하기
파이썬 프로퍼티 디스크립터 이해하기파이썬 프로퍼티 디스크립터 이해하기
파이썬 프로퍼티 디스크립터 이해하기
 
RAPID - Building a highly usable API Design language with XText
RAPID - Building a highly usable API Design language with XTextRAPID - Building a highly usable API Design language with XText
RAPID - Building a highly usable API Design language with XText
 
Unity で実装するエイジングテストのお話
Unity で実装するエイジングテストのお話Unity で実装するエイジングテストのお話
Unity で実装するエイジングテストのお話
 
iPhoneでリアルタイムマルチプレイを実現!Photon Network Engine
iPhoneでリアルタイムマルチプレイを実現!Photon Network EngineiPhoneでリアルタイムマルチプレイを実現!Photon Network Engine
iPhoneでリアルタイムマルチプレイを実現!Photon Network Engine
 
Understanding open max il
Understanding open max ilUnderstanding open max il
Understanding open max il
 
Test-Driven Development of Xtext DSLs
Test-Driven Development  of Xtext DSLsTest-Driven Development  of Xtext DSLs
Test-Driven Development of Xtext DSLs
 
GDC Europe 2014: Unreal Engine 4 for Programmers - Lessons Learned & Things t...
GDC Europe 2014: Unreal Engine 4 for Programmers - Lessons Learned & Things t...GDC Europe 2014: Unreal Engine 4 for Programmers - Lessons Learned & Things t...
GDC Europe 2014: Unreal Engine 4 for Programmers - Lessons Learned & Things t...
 
ビジュアルスクリプティング (旧:Bolt) で始めるUnity入門3日目 ゲームをカスタマイズしよう
ビジュアルスクリプティング (旧:Bolt) で始めるUnity入門3日目 ゲームをカスタマイズしようビジュアルスクリプティング (旧:Bolt) で始めるUnity入門3日目 ゲームをカスタマイズしよう
ビジュアルスクリプティング (旧:Bolt) で始めるUnity入門3日目 ゲームをカスタマイズしよう
 
Jenkins 2を使った究極のpipeline ~ 明日もう一度来てください、本物のpipelineをお見せしますよ ~
Jenkins 2を使った究極のpipeline ~ 明日もう一度来てください、本物のpipelineをお見せしますよ ~Jenkins 2を使った究極のpipeline ~ 明日もう一度来てください、本物のpipelineをお見せしますよ ~
Jenkins 2を使った究極のpipeline ~ 明日もう一度来てください、本物のpipelineをお見せしますよ ~
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytest
 
はじめてのUnreal Engine 4
はじめてのUnreal Engine 4はじめてのUnreal Engine 4
はじめてのUnreal Engine 4
 
[143] Modern C++ 무조건 써야 해?
[143] Modern C++ 무조건 써야 해?[143] Modern C++ 무조건 써야 해?
[143] Modern C++ 무조건 써야 해?
 
How we optimized our Game - Jake & Tess' Finding Monsters Adventure
How we optimized our Game - Jake & Tess' Finding Monsters AdventureHow we optimized our Game - Jake & Tess' Finding Monsters Adventure
How we optimized our Game - Jake & Tess' Finding Monsters Adventure
 
Unity Roadmap 2020: Core Engine & Creator Tools
Unity Roadmap 2020: Core Engine & Creator ToolsUnity Roadmap 2020: Core Engine & Creator Tools
Unity Roadmap 2020: Core Engine & Creator Tools
 
Py.test
Py.testPy.test
Py.test
 
Unity 2018-2019を見据えたDeNAのUnity開発のこれから [DeNA TechCon 2019]
Unity 2018-2019を見据えたDeNAのUnity開発のこれから [DeNA TechCon 2019]Unity 2018-2019を見据えたDeNAのUnity開発のこれから [DeNA TechCon 2019]
Unity 2018-2019を見据えたDeNAのUnity開発のこれから [DeNA TechCon 2019]
 
Android Multimedia Framework
Android Multimedia FrameworkAndroid Multimedia Framework
Android Multimedia Framework
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applications
 

Similar to Work With Images

Universal Image Loader: Story, Architecture, FAQ
Universal Image Loader: Story, Architecture, FAQUniversal Image Loader: Story, Architecture, FAQ
Universal Image Loader: Story, Architecture, FAQSergey Tarasevich
 
Android - Displaying images
Android - Displaying imagesAndroid - Displaying images
Android - Displaying imagesMatteo Bonifazi
 
Kotlin Mullets
Kotlin MulletsKotlin Mullets
Kotlin MulletsJames Ward
 
Printing photos-html-using-android
Printing photos-html-using-androidPrinting photos-html-using-android
Printing photos-html-using-androidKetan Raval
 
Palestra - Utilizando tensorflow mobile e seus desafios
Palestra - Utilizando tensorflow mobile e seus desafiosPalestra - Utilizando tensorflow mobile e seus desafios
Palestra - Utilizando tensorflow mobile e seus desafiosGustavo Monteiro
 
What is image in Swift?/はるふ
What is image in Swift?/はるふWhat is image in Swift?/はるふ
What is image in Swift?/はるふha1f Yamaguchi
 
Total Knockout: Start-to-Finish Development of Suitability Applications Using...
Total Knockout: Start-to-Finish Development of Suitability Applications Using...Total Knockout: Start-to-Finish Development of Suitability Applications Using...
Total Knockout: Start-to-Finish Development of Suitability Applications Using...Blue Raster
 
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficientTh 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficientBin Shao
 
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
 
カメラアプリ実装のコツ
カメラアプリ実装のコツカメラアプリ実装のコツ
カメラアプリ実装のコツtac0x2a
 
Getting Intimate with Images on Android with James Halpern
Getting Intimate with Images on Android with James HalpernGetting Intimate with Images on Android with James Halpern
Getting Intimate with Images on Android with James HalpernFITC
 
Android UI Tips & Tricks
Android UI Tips & TricksAndroid UI Tips & Tricks
Android UI Tips & TricksDroidConTLV
 
426 lecture 4: AR Developer Tools
426 lecture 4: AR Developer Tools426 lecture 4: AR Developer Tools
426 lecture 4: AR Developer ToolsMark Billinghurst
 
Annotation tools for ADAS & Autonomous Driving
Annotation tools for ADAS & Autonomous DrivingAnnotation tools for ADAS & Autonomous Driving
Annotation tools for ADAS & Autonomous DrivingYu Huang
 
Fragments: Why, How, What For?
Fragments: Why, How, What For?Fragments: Why, How, What For?
Fragments: Why, How, What For?Brenda Cook
 
Building mobile apps with the ArcGIS api for Javascript, Esri, Andy Gup and A...
Building mobile apps with the ArcGIS api for Javascript, Esri, Andy Gup and A...Building mobile apps with the ArcGIS api for Javascript, Esri, Andy Gup and A...
Building mobile apps with the ArcGIS api for Javascript, Esri, Andy Gup and A...Esri Nederland
 
Android ui tips & tricks
Android ui tips & tricksAndroid ui tips & tricks
Android ui tips & tricksShem Magnezi
 
HTML5 - Chances and Pitfalls (Bytro Labs GmbH)
HTML5 - Chances and Pitfalls (Bytro Labs GmbH)HTML5 - Chances and Pitfalls (Bytro Labs GmbH)
HTML5 - Chances and Pitfalls (Bytro Labs GmbH)Felix Faber
 

Similar to Work With Images (20)

Bitmap management like a boss
Bitmap management like a bossBitmap management like a boss
Bitmap management like a boss
 
Universal Image Loader: Story, Architecture, FAQ
Universal Image Loader: Story, Architecture, FAQUniversal Image Loader: Story, Architecture, FAQ
Universal Image Loader: Story, Architecture, FAQ
 
Android - Displaying images
Android - Displaying imagesAndroid - Displaying images
Android - Displaying images
 
Kotlin Mullets
Kotlin MulletsKotlin Mullets
Kotlin Mullets
 
Printing photos-html-using-android
Printing photos-html-using-androidPrinting photos-html-using-android
Printing photos-html-using-android
 
Palestra - Utilizando tensorflow mobile e seus desafios
Palestra - Utilizando tensorflow mobile e seus desafiosPalestra - Utilizando tensorflow mobile e seus desafios
Palestra - Utilizando tensorflow mobile e seus desafios
 
What is image in Swift?/はるふ
What is image in Swift?/はるふWhat is image in Swift?/はるふ
What is image in Swift?/はるふ
 
Total Knockout: Start-to-Finish Development of Suitability Applications Using...
Total Knockout: Start-to-Finish Development of Suitability Applications Using...Total Knockout: Start-to-Finish Development of Suitability Applications Using...
Total Knockout: Start-to-Finish Development of Suitability Applications Using...
 
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficientTh 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
 
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
 
カメラアプリ実装のコツ
カメラアプリ実装のコツカメラアプリ実装のコツ
カメラアプリ実装のコツ
 
Getting Intimate with Images on Android with James Halpern
Getting Intimate with Images on Android with James HalpernGetting Intimate with Images on Android with James Halpern
Getting Intimate with Images on Android with James Halpern
 
Android UI Tips & Tricks
Android UI Tips & TricksAndroid UI Tips & Tricks
Android UI Tips & Tricks
 
426 lecture 4: AR Developer Tools
426 lecture 4: AR Developer Tools426 lecture 4: AR Developer Tools
426 lecture 4: AR Developer Tools
 
Supercharge your ui
Supercharge your uiSupercharge your ui
Supercharge your ui
 
Annotation tools for ADAS & Autonomous Driving
Annotation tools for ADAS & Autonomous DrivingAnnotation tools for ADAS & Autonomous Driving
Annotation tools for ADAS & Autonomous Driving
 
Fragments: Why, How, What For?
Fragments: Why, How, What For?Fragments: Why, How, What For?
Fragments: Why, How, What For?
 
Building mobile apps with the ArcGIS api for Javascript, Esri, Andy Gup and A...
Building mobile apps with the ArcGIS api for Javascript, Esri, Andy Gup and A...Building mobile apps with the ArcGIS api for Javascript, Esri, Andy Gup and A...
Building mobile apps with the ArcGIS api for Javascript, Esri, Andy Gup and A...
 
Android ui tips & tricks
Android ui tips & tricksAndroid ui tips & tricks
Android ui tips & tricks
 
HTML5 - Chances and Pitfalls (Bytro Labs GmbH)
HTML5 - Chances and Pitfalls (Bytro Labs GmbH)HTML5 - Chances and Pitfalls (Bytro Labs GmbH)
HTML5 - Chances and Pitfalls (Bytro Labs GmbH)
 

Recently uploaded

Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 

Recently uploaded (20)

Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 

Work With Images

Editor's Notes

  1. О чем я сегодня буду рассказывать: - Сначала вкратце о поддерживаемых изображениях в Андроид - Разберем главный виджет для отображения картинок – ImageView, рассмотрим его возможности и предоставляемые параметры - Далее мы рассмотрим специфику хранения изображений в памяти посредством класса, заглянем внутрь класса - И рассмотрим API Андроида, с помощью которого можно формировать объекты данного класса - Далее рассмотрим best practises по загрузке, декодированию и отображению изображений (больших и маленьких) на Андроид - В конце я расскажу о парочке проблем, с которыми я столкнулся в процессе работы над своей опен-сорс библиотекой для отображения картинок и способах их рещениях. И как обещанный бонус в конце: на основе своего опыта создания самой популярной Андроид-библиотеки на ГитХабе, я приведу свое видение необходимых действий для продвижения своего опен-сорс проекта, если вдруг кто-нибудь захочет создать свою либу.
  2. Итак начнем. На данный момент поддерживаются 5 форматов.
  3. Откуда мы можем загружать картинки? - ресурсы приложения – drawables (подготовленные под разные плотности экрана) или assets - локальные файлы на файловой системе девайса или внешней SD карточки - картинки на удаленных серверах (т.е. интернет) - откуда-нибудь еще, например из SQLite базы…
  4. Для отображения картинок в UI в Андроид имеется виждет ImageView. В XML-лэйауте от представляется так. Он предоставляет возможности не только отображать картинки, - но и менять отображение, масштабируя картинку под свои нужды, - с использованием матрицы преобразований или без, - а также применять цветовые преобразования.
  5. Java-класс виждета - ImageView – имеет следующие методы для отображения картинок: -
  6. Вернемся к XML объявлению. ImageView добавлеяет собственные параметры, по сравнению с View, они представлены на слайде. Я не буду рассматривать параметры baseline и tint, но плотно разберу остальные параметры: - src – rerefence на картинку из ресурсов - scaleType мы сейчас детально разберем на примере
  7. Вот тут начинается самое интересное, если в дело вступаетa adjustViewBounds параметр. Его задача отобразить картинку в ImageView, а затем подогнать размеры вьюшки под размеры картинки, чтобы «ничего не выпирало», так сказать  Т.е.по сути мы не должны видеть бэкграунд ImageView какой бы он там ни был, т.к. границы вьюшки должны строго оборачивать отображенную картинку.
  8. Итак, почему же происходит? Все становится понятно, если заглянуть в метод setAdjustViewBounds(). И мы видим там, что adjustViewBounds делает “неявно” FitCenter scaleType. Ну как неявно…. Если заглянуть в этот метод – то все явно. Но до этого не очевидно.
  9. Давайте попробуем поставить scaleType="centerCrop” и добавить padding, скажем 20 дип. Вот такой результат мы получим. На вопрос «Какого…?» есть ответ в виде параметра cropToPadding
  10. Только с выставленным cropToPadding=“true” мы получим ожидаемый результат. А без него мы либо не получим нужных паддингов, либо получим их частично.
  11. Вообще можно выделить парочку неочевидных моментов с ImageView, которые могут вызвать недоумение по началу, когда еще не приходилось сталкиваться с той или иной проблемой. Первая из них это ранее упомянутая особенность setAdjustViewBounds(), которая сбрасыват scaleType к FIT_CENTER. Стоит это учитывать при использовании этого параметра, дабы не биться головой «как оно так скейлится». Следующий момент - это использование матрицы преобразований, которую можно засетить ImageView. Нетронутой ваша матрица останется только при условии что ScaleType == MATRIX. При FIT_XY ваша матрица вообще не будет учитываться, а при остальных scaleType’ах к матрице будут добавлены/переписаны дополнительные преобразования, соответствующие конкретному scaleType. Следующиймомент – значения maxWidth & maxHeight будут учитываться только если works only if adjustViewBounds="true“. Ну и последний упомянутый момент насчет паддингов, которые могут работать странно для скейлТапов CENTER, CENTER_CROP и MATRIX
  12. Окей, отойдем от виджетов и перейдем непосредственно к картинкам и тому, как они представляются в памяти. А представляются они как битмапы («битовые карты»), т.е. объекты класса Битмпа.
  13. А что битмап это по сути пиксели: набор пикселей которые формируют картинку. Но тут есть одна интересная особенность в Андроид – где эти пиксели хранятся.
  14. На Андроид 2.3.3 и ниже, данные о пикселях хранились в нативной памяти, т.е. были отделены от самого объекта Битмап, которые находился в куче Далвик машины. Эти пиксели в нативной памяти не освобождались так, чтобы это можно было предсказать. А это могло вызвать перерасход памяти и крэш. Начиная с Андроид Android 3.0, пиксели хранятся в куче Далвик наряду с соответствующей битмапой.
  15. На Android 2.3.3 и ниже рекомендуется использовать recycle(). Если вы отображаете большие картинки в своем приложении, вы вероятнее всего, отхватите рано или поздно OutOfMemoryError. Метод recycle() позволяет приложению освободить память под пиксель-дата as soon as possible. Но тут нужно быть осторожным: recycle() следует использовать только тогда, когда вы уверены, что битмапка не будет использоваться далее. Если вы вызовите recycle() на отображенной битмапке или попробуете отобразить заресайкленную битмапку – вы получите ошибку: "Canvas: trying to use a recycled bitmap".
  16. На 3.0 и выше теперь pixel-data, как и Битмап, может быть собрана сборщиком мусора. Однако пиксель-дата – это не поле в Битмап, типа массив байт. Такого в классе Битмап нет. Есть поле mNativeBitmap типа long, о котором я расскажу чуть позже.
  17. Я все говорю о пикселях, а что такое пиксель в памяти? Это байты кончено. По кодировке ARGB пиксель обычно задается 4 каналами: альфа-канал, и три канала цветов – красного, зеленого и синего. Так вот под каждый канал можно отводить разное количество бит, что влияет на свойства и качество изображения. В Андроид есть следующие конфигурации представления пикселей: - ALPHA_8 – пиксель несет информации только об прозрачности, т.е. никакой цветовой информации. 1 байт - RGB_565 – пиксель не несет информации об альфа канале, только RGB. – 2 байт - ARGB_4444 - пиксель имеет все каналы, но по 4 бита на каждый. Задепрекейчен с API 13 (Android 3.2). А начиная с 19 (KITKAT), любая битмапка, созданная под ARGB_4444 будет все равно создана под ARGB_8888. - ARGB_8888 – самая качественная конфигурация.
  18. Теперь рассмотрим класс Битмап внутри и снаружи.
  19. Если заглянуть внутрь клаасса можно обнаружить следующие основные поля внутри. mNativeBitmap – как я упоминал ранее, скорее всего адрес пискелей в нативной памяти. А начиная с 3.0 возможно адрес в куче, но я не уверен. mDensity – определяет под какую плотность рассчитана данная битмапка. По умолчанию – плотность экрана. mIsMutable – можно ли менять пиксели в битмапке mRecycled – упразднена ли битмапка, т.е. уничтожены ли ее пиксели. Если так – то при попытке отобразить ее в UI или доступиться к пикселям произойдет ошибка(исключение) mRequestPremultiplied – нужно ли пред-перемножение пикселей при формировании битмапки. Параметр важен только для картинок с наличием прозрачности, в конфигурации ARGB_8888. Что за пред-перемножение такое я расскажу позже подробно.
  20. Чтобы создать объект Битмап у класса есть следующие статические методы:
  21. Однако обычно нам нужно задекодировать какой-нибудь файл или стрим в Битмап объект. Для этого есть класс BitmapFactory и его статические методы. (КЛИК) Все они могут принимать в конце Options, которые влияют на то, какой битмап мы получим в результате. (КЛИК)
  22. В Options, который состоит из кучи паблик полей, у нас есть входные и выходные поля. Входные поля нужно засетить нам до декодирования, выходные будут заполнены после декодирования. Сейчас пройдемся по каждому из полей.
  23. inDither Если тру - то декодер попытается сгладить изображение. inPreferredConfig If this is non-null, the decoder will try to decode into this internal configuration. If it is null, or the request cannot be met, the decoder will try to pick the best matching config based on the system's screen depth, and characteristics of the original image such as if it has per-pixel alpha (requiring a config that also does). Image are loaded with the ARGB_8888 config by default. inSampleSize If set to a value > 1, requests the decoder to subsample the original image, returning a smaller image to save memory. The sample size is the number of pixels in either dimension that correspond to a single pixel in the decoded bitmap. For example, inSampleSize == 4 returns an image that is 1/4 the width/height of the original, and 1/16 the number of pixels. Any value <= 1 is treated the same as 1. Note: the decoder uses a final value based on powers of 2, any other value will be rounded down to the nearest power of 2. inTempStorage Temp storage to use for decoding. Suggest 16K or so.
  24. inDensity The pixel density to use for the bitmap. This will always result in the returned bitmap having a density set for it (see Bitmap.setDensity(int)). In addition, if inScaled is set (which it is by default} and this density does not match inTargetDensity, then the bitmap will be scaled to the target density before being returned. If this is 0, decodeResource(Resources, int), decodeResource(Resources, int, android.graphics.BitmapFactory.Options), and decodeResourceStream(Resources, TypedValue, InputStream, Rect, BitmapFactory.Options) will fill in the density associated with the resource. The other functions will leave it as-is and no density will be applied. inTargetDensity The pixel density of the destination this bitmap will be drawn to. This is used in conjunction with inDensity and inScaled to determine if and how to scale the bitmap before returning it. If this is 0, decodeResource(Resources, int), decodeResource(Resources, int, android.graphics.BitmapFactory.Options), and decodeResourceStream(Resources, TypedValue, InputStream, Rect, BitmapFactory.Options) will fill in the density associated the Resources object's DisplayMetrics. The other functions will leave it as-is and no scaling for density will be performed. inScreenDensity The pixel density of the actual screen that is being used. This is purely for applications running in density compatibility code, where inTargetDensity is actually the density the application sees rather than the real screen density. By setting this, you allow the loading code to avoid scaling a bitmap that is currently in the screen density up/down to the compatibility density. Instead, if inDensity is the same as inScreenDensity, the bitmap will be left as-is. Anything using the resulting bitmap must also used Bitmap.getScaledWidth and Bitmap.getScaledHeight to account for any different between the bitmap's density and the target's density. This is never set automatically for the caller by BitmapFactory itself. It must be explicitly set, since the caller must deal with the resulting bitmap in a density-aware way. inScaled When this flag is set, if inDensity and inTargetDensity are not 0, the bitmap will be scaled to match inTargetDensity when loaded, rather than relying on the graphics system scaling it each time it is drawn to a Canvas. BitmapRegionDecoder ignores this flag, and will not scale output based on density. (though inSampleSize is supported) This flag is turned on by default and should be turned off if you need a non-scaled version of the bitmap. Nine-patch bitmaps ignore this flag and are always scaled. If inPremultiplied is set to false, and the image has alpha, setting this flag to true may result in incorrect colors. inInputShareable As of LOLLIPOP, this is ignored. In KITKAT and below, this field works in conjuction with inPurgeable. If inPurgeable is false, then this field is ignored. If inPurgeable is true, then this field determines whether the bitmap can share a reference to the input data (inputstream, array, etc.) or if it must make a deep copy. inPurgeable As of LOLLIPOP, this is ignored. In KITKAT and below, if this is set to true, then the resulting bitmap will allocate its pixels such that they can be purged if the system needs to reclaim memory. In that instance, when the pixels need to be accessed again (e.g. the bitmap is drawn, getPixels() is called), they will be automatically re-decoded. For the re-decode to happen, the bitmap must have access to the encoded data, either by sharing a reference to the input or by making a copy of it. This distinction is controlled by inInputShareable. If this is true, then the bitmap may keep a shallow reference to the input. If this is false, then the bitmap will explicitly make a copy of the input data, and keep that. Even if sharing is allowed, the implementation may still decide to make a deep copy of the input data. While inPurgeable can help avoid big Dalvik heap allocations (from API level 11 onward), it sacrifices performance predictability since any image that the view system tries to draw may incur a decode delay which can lead to dropped frames. Therefore, most apps should avoid using inPurgeable to allow for a fast and fluid UI. To minimize Dalvik heap allocations use the inBitmap flag instead. flag is ignored when used with decodeResource(Resources, int, android.graphics.BitmapFactory.Options) or decodeFile(String, android.graphics.BitmapFactory.Options).
  25. inPreferQualityOverSpeed If it is set to true, the decoder will try to decode the reconstructed image to a higher quality even at the expense of the decoding speed. Currently the field only affects JPEG decode, in the case of which a more accurate, but slightly slower, IDCT method will be used instead. inMutable If set, decode methods will always return a mutable Bitmap instead of an immutable one. This can be used for instance to programmatically apply effects to a Bitmap loaded through BitmapFactory. inPremultiplied If true (which is the default), the resulting bitmap will have its color channels pre-multipled by the alpha channel. This should NOT be set to false for images to be directly drawn by the view system or through a Canvas. The view system and Canvas assume all drawn images are pre-multiplied to simplify draw-time blending, and will throw a RuntimeException when un-premultiplied are drawn. This is likely only useful if you want to manipulate raw encoded image data, e.g. with RenderScript or custom OpenGL. This does not affect bitmaps without an alpha channel. Setting this flag to false while setting inScaled to true may result in incorrect colors.
  26. If set, decode methods that take the Options object will attempt to reuse this bitmap when loading content. If the decode operation cannot use this bitmap, the decode method will return null and will throw an IllegalArgumentException. The current implementation necessitates that the reused bitmap be mutable, and the resulting reused bitmap will continue to remain mutable even when decoding a resource which would normally result in an immutable bitmap. You should still always use the returned Bitmap of the decode method and not assume that reusing the bitmap worked, due to the constraints outlined above and failure situations that can occur. Checking whether the return value matches the value of the inBitmap set in the Options structure will indicate if the bitmap was reused, but in all cases you should use the Bitmap returned by the decoding function to ensure that you are using the bitmap that was used as the decode destination.
  27. If set, decode methods that take the Options object will attempt to reuse this bitmap when loading content. If the decode operation cannot use this bitmap, the decode method will return null and will throw an IllegalArgumentException. The current implementation necessitates that the reused bitmap be mutable, and the resulting reused bitmap will continue to remain mutable even when decoding a resource which would normally result in an immutable bitmap. You should still always use the returned Bitmap of the decode method and not assume that reusing the bitmap worked, due to the constraints outlined above and failure situations that can occur. Checking whether the return value matches the value of the inBitmap set in the Options structure will indicate if the bitmap was reused, but in all cases you should use the Bitmap returned by the decoding function to ensure that you are using the bitmap that was used as the decode destination. Usage with BitmapFactory As of KITKAT, any mutable bitmap can be reused by BitmapFactory to decode any other bitmaps as long as the resulting byte count of the decoded bitmap is less than or equal to the allocated byte count of the reused bitmap. This can be because the intrinsic size is smaller, or its size post scaling (for density / sample size) is smaller. Prior to KITKAT additional constraints apply: The image being decoded (whether as a resource or as a stream) must be in jpeg or png format. Only equal sized bitmaps are supported, with inSampleSize set to 1. Additionally, the configuration of the reused bitmap will override the setting of inPreferredConfig, if set. Usage with BitmapRegionDecoder BitmapRegionDecoder will draw its requested content into the Bitmap provided, clipping if the output content size (post scaling) is larger than the provided Bitmap. The provided Bitmap's width, height, and Bitmap.Config will not be changed. BitmapRegionDecoder support for inBitmap was introduced in JELLY_BEAN. All formats supported by BitmapRegionDecoder support Bitmap reuse via inBitmap.
  28. Помимо BitmapFactory не стоит забывать о BitmapRegionDecoder, который позволяет декодировать часть картинки в Битмап, а не всю. inBitmap поле в Options также поддерживается с версии Android 4.1 (API 16).
  29. Хватит декодировать картинки, нужно немного и наоборот. Как записать Битмапку в файл – с помощью метода compress. На вход…
  30. А теперь прогоним всю последовательность от загрузки до отображения картинки. Картинки приходят к нам в различных формах и размерах. В множестве случаев они больше, чем требуется для отображения в UI. Учитывая, что мы работаем с ограниченной памятью, в идеале нам нужно грузить уменьшенную копию картинки в память. Уменьшенная версия должна соответствовать размеру UI компонента, в котором она отображается. Картинка более высокого разрешения не даст никакого визуального выигрыша, а только будет занимать больше памяти и требовать больше производительных ресурсов для дополнительного скейлинга.
  31. Returns null
  32. Note: In the past, a popular memory cache implementation was a SoftReference or WeakReference bitmap cache, however this is not recommended. Starting from Android 2.3 (API Level 9) the garbage collector is more aggressive with collecting soft/weak references which makes them fairly ineffective. In addition, prior to Android 3.0 (API Level 11), the backing data of a bitmap was stored in native memory which is not released in a predictable manner, potentially causing an application to briefly exceed its memory limits and crash.