Balu Sangem
NOSORT
Published in
2 min readJun 29, 2018

--

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 the createSource 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:

Screenshot with default configurations

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 created decoder

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 :

Screenshot after using post processor to create Circular Drawable

Extras

  • Bitmap or Drawable created by ImageDecorder is Immutable (isMutable() returns fasle ) , these properties can be changed by using setMutableRequired(true) (only works for Bitmap)
  • If the encoded image is incomplete or contains an error, or if an Exception occurs during decoding, a DecodeException will be thrown. use setOnPartialImageListener on decoder to show partial Image.

Thanks for Reading!

--

--

Balu Sangem
NOSORT
Editor for

Software Engineer @Everest.Engineering , Software design learner.