2. Who’s this man?
Sergey Tarasevich (@nostra13)
• Android developer at CactusSoft
• Author of «Universal Image Loader» library
• Certified Java SE 7 Programmer
3. 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
43. 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"
46. 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 =
47. 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()
48. 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
51. Bitmap Inside
• long mNativeBitmap
• int mWidth
• int mHeight
• int mDensity
• boolean mIsMutable
• boolean mRecycled
• boolean mRequestPremultiplied
52. 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)
58. 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
59. 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
63. 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
64. 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;
66. 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?
67. Disk cache
Save images before caching in memory
and/or
Save bitmaps after caching in memory
68. 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
69. Manage memory (>= API 11)
• Use BitmapFactory.Options.inBitmap
(only if bitmap is no longer being used)
LruCache<String, Bitmap> mMemoryCache;
Set<SoftReference<Bitmap>> mReusableBitmaps;
71. Issue #1
Bitmap bmp = BitmapFactory.decodeFile(imagePath);
...
imageView.setImageBitmap(bmp);
“Bitmap too large to be uploaded into a
texture (2592x1944, max=2048x2048)”
72. 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
73. Issue #2
Bitmap scaledBmp =
Bitmap.createScaledBitmap(originalBmp, ...);
originalBmp.recycle();
imageView.setImageBitmap(scaledBmp);
“java.lang.RuntimeException:
Canvas: trying to use a recycled bitmap…”
74. 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);
76. 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)
О чем я сегодня буду рассказывать:
- Сначала вкратце о поддерживаемых изображениях в Андроид
- Разберем главный виджет для отображения картинок – ImageView, рассмотрим его возможности и предоставляемые параметры
- Далее мы рассмотрим специфику хранения изображений в памяти посредством класса, заглянем внутрь класса
- И рассмотрим API Андроида, с помощью которого можно формировать объекты данного класса
- Далее рассмотрим best practises по загрузке, декодированию и отображению изображений (больших и маленьких) на Андроид
- В конце я расскажу о парочке проблем, с которыми я столкнулся в процессе работы над своей опен-сорс библиотекой для отображения картинок и способах их рещениях.
И как обещанный бонус в конце: на основе своего опыта создания самой популярной Андроид-библиотеки на ГитХабе, я приведу свое видение необходимых действий для продвижения своего опен-сорс проекта, если вдруг кто-нибудь захочет создать свою либу.
Итак начнем. На данный момент поддерживаются 5 форматов.
Откуда мы можем загружать картинки?
- ресурсы приложения – drawables (подготовленные под разные плотности экрана) или assets
- локальные файлы на файловой системе девайса или внешней SD карточки
- картинки на удаленных серверах (т.е. интернет)
- откуда-нибудь еще, например из SQLite базы…
Для отображения картинок в UI в Андроид имеется виждет ImageView. В XML-лэйауте от представляется так.
Он предоставляет возможности не только отображать картинки,
- но и менять отображение, масштабируя картинку под свои нужды,
- с использованием матрицы преобразований или без,
- а также применять цветовые преобразования.
Java-класс виждета - ImageView – имеет следующие методы для отображения картинок:
-
Вернемся к XML объявлению. ImageView добавлеяет собственные параметры, по сравнению с View, они представлены на слайде.
Я не буду рассматривать параметры baseline и tint, но плотно разберу остальные параметры:
- src – rerefence на картинку из ресурсов
- scaleType мы сейчас детально разберем на примере
Вот тут начинается самое интересное, если в дело вступаетa adjustViewBounds параметр. Его задача отобразить картинку в ImageView, а затем подогнать размеры вьюшки под размеры картинки, чтобы «ничего не выпирало», так сказать Т.е.по сути мы не должны видеть бэкграунд ImageView какой бы он там ни был, т.к. границы вьюшки должны строго оборачивать отображенную картинку.
Итак, почему же происходит? Все становится понятно, если заглянуть в метод setAdjustViewBounds(). И мы видим там, что adjustViewBounds делает “неявно” FitCenter scaleType.
Ну как неявно…. Если заглянуть в этот метод – то все явно. Но до этого не очевидно.
Давайте попробуем поставить scaleType="centerCrop” и добавить padding, скажем 20 дип.
Вот такой результат мы получим.
На вопрос «Какого…?» есть ответ в виде параметра cropToPadding
Только с выставленным cropToPadding=“true” мы получим ожидаемый результат.
А без него мы либо не получим нужных паддингов, либо получим их частично.
Вообще можно выделить парочку неочевидных моментов с ImageView, которые могут вызвать недоумение по началу, когда еще не приходилось сталкиваться с той или иной проблемой.
Первая из них это ранее упомянутая особенность setAdjustViewBounds(), которая сбрасыват scaleType к FIT_CENTER. Стоит это учитывать при использовании этого параметра, дабы не биться головой «как оно так скейлится».
Следующий момент - это использование матрицы преобразований, которую можно засетить ImageView. Нетронутой ваша матрица останется только при условии что ScaleType == MATRIX. При FIT_XY ваша матрица вообще не будет учитываться, а при остальных scaleType’ах к матрице будут добавлены/переписаны дополнительные преобразования, соответствующие конкретному scaleType.
Следующиймомент – значения maxWidth & maxHeight будут учитываться только если works only if adjustViewBounds="true“.
Ну и последний упомянутый момент насчет паддингов, которые могут работать странно для скейлТапов CENTER, CENTER_CROP и MATRIX
Окей, отойдем от виджетов и перейдем непосредственно к картинкам и тому, как они представляются в памяти.
А представляются они как битмапы («битовые карты»), т.е. объекты класса Битмпа.
А что битмап это по сути пиксели: набор пикселей которые формируют картинку.
Но тут есть одна интересная особенность в Андроид – где эти пиксели хранятся.
На Андроид 2.3.3 и ниже, данные о пикселях хранились в нативной памяти, т.е. были отделены от самого объекта Битмап, которые находился в куче Далвик машины. Эти пиксели в нативной памяти не освобождались так, чтобы это можно было предсказать. А это могло вызвать перерасход памяти и крэш.
Начиная с Андроид Android 3.0, пиксели хранятся в куче Далвик наряду с соответствующей битмапой.
На Android 2.3.3 и ниже рекомендуется использовать recycle(). Если вы отображаете большие картинки в своем приложении, вы вероятнее всего, отхватите рано или поздно OutOfMemoryError. Метод recycle() позволяет приложению освободить память под пиксель-дата as soon as possible.
Но тут нужно быть осторожным: recycle() следует использовать только тогда, когда вы уверены, что битмапка не будет использоваться далее. Если вы вызовите recycle() на отображенной битмапке или попробуете отобразить заресайкленную битмапку – вы получите ошибку: "Canvas: trying to use a recycled bitmap".
На 3.0 и выше теперь pixel-data, как и Битмап, может быть собрана сборщиком мусора.
Однако пиксель-дата – это не поле в Битмап, типа массив байт. Такого в классе Битмап нет. Есть поле mNativeBitmap типа long, о котором я расскажу чуть позже.
Я все говорю о пикселях, а что такое пиксель в памяти? Это байты кончено.
По кодировке 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 – самая качественная конфигурация.
Теперь рассмотрим класс Битмап внутри и снаружи.
Если заглянуть внутрь клаасса можно обнаружить следующие основные поля внутри.
mNativeBitmap – как я упоминал ранее, скорее всего адрес пискелей в нативной памяти. А начиная с 3.0 возможно адрес в куче, но я не уверен.
mDensity – определяет под какую плотность рассчитана данная битмапка. По умолчанию – плотность экрана.
mIsMutable – можно ли менять пиксели в битмапке
mRecycled – упразднена ли битмапка, т.е. уничтожены ли ее пиксели. Если так – то при попытке отобразить ее в UI или доступиться к пикселям произойдет ошибка(исключение)
mRequestPremultiplied – нужно ли пред-перемножение пикселей при формировании битмапки. Параметр важен только для картинок с наличием прозрачности, в конфигурации ARGB_8888. Что за пред-перемножение такое я расскажу позже подробно.
Чтобы создать объект Битмап у класса есть следующие статические методы:
Однако обычно нам нужно задекодировать какой-нибудь файл или стрим в Битмап объект.
Для этого есть класс BitmapFactory и его статические методы.
(КЛИК)
Все они могут принимать в конце Options, которые влияют на то, какой битмап мы получим в результате.
(КЛИК)
В Options, который состоит из кучи паблик полей, у нас есть входные и выходные поля.
Входные поля нужно засетить нам до декодирования, выходные будут заполнены после декодирования.
Сейчас пройдемся по каждому из полей.
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.
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).
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.
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.
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.
Помимо BitmapFactory не стоит забывать о BitmapRegionDecoder, который позволяет декодировать часть картинки в Битмап, а не всю.
inBitmap поле в Options также поддерживается с версии Android 4.1 (API 16).
Хватит декодировать картинки, нужно немного и наоборот. Как записать Битмапку в файл – с помощью метода compress.
На вход…
А теперь прогоним всю последовательность от загрузки до отображения картинки.
Картинки приходят к нам в различных формах и размерах. В множестве случаев они больше, чем требуется для отображения в UI.
Учитывая, что мы работаем с ограниченной памятью, в идеале нам нужно грузить уменьшенную копию картинки в память. Уменьшенная версия должна соответствовать размеру UI компонента, в котором она отображается.
Картинка более высокого разрешения не даст никакого визуального выигрыша, а только будет занимать больше памяти и требовать больше производительных ресурсов для дополнительного скейлинга.
Returns null
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.