A class for converting encoded images (like PNG
, JPEG
, WEBP
, GIF
, or HEIF
) into Drawable
or Bitmap
objects.
ImageDecoder class is available from android P the Framework so we can only use it on devices running P or later for now.
- First we have to create
Source
using one of thecreateSource
overloads.
val source = ImageDecoder.createSource(X);
//Where X is a file or id from resource or name from assets
- To get image with default configurations , we can use
decodeDrawable(source)
Complete Code to get bitmap with default configurations
//getting image from assets
val source = ImageDecoder.createSource(assets, "image.jpg")
val bitmap = ImageDecoder.decodeBitmap(source) //default
imageView.setImageBitmap(bitmap)
Same way we can create Drawable with default configurations
//getting image form assets
val source = ImageDecoder.createSource(assets,"image.jpg")
val drawable = ImageDecoder.decodeDrawable(source)
imageView.setImageDrawable(drawable)
Result is:
To change default settings, we can pass OnHeaderDecodedListener as listener for decodeDrawable(source,listenr)
- For Example,to create a image with width and height ,call
setTargetSize(width,height)
OnHeaderDecodedListener
interface has single methodonHeaderDecoded(decoder,imageinfo,source)
- decoder (
ImageDecoder)
: the object performing the decode, - imageinfo (
ImageDecoder.ImageInfo
) : information about the encoded image for example height and width. - source (
ImageDecorder.Source
) : object that createddecoder
If decoded image is GIF
or WEBP
decodeResource will return an AnimatedImageDrawable , To start animation call start()
on drawble.
val drawable = ImageDecoder.decodeDrawable(source)
if (drawable is AnimatedImageDrawable) {
drawable.start()
}
Creating a Circular Drawable using ImageDecoder’s PostProcessor
Result is :
Extras
- Bitmap or Drawable created by ImageDecorder is Immutable (
isMutable()
returnsfasle
) , these properties can be changed by usingsetMutableRequired(true)
(only works for Bitmap) - If the encoded image is incomplete or contains an error, or if an
Exception
occurs during decoding, aDecodeException
will be thrown. usesetOnPartialImageListener
ondecoder
to show partial Image.
Thanks for Reading!