Sdílet prostřednictvím


ImageDecoder Class

Definition

A class for converting encoded images (like PNG, JPEG, WEBP, GIF, or HEIF) into Drawable or Bitmap objects.

[Android.Runtime.Register("android/graphics/ImageDecoder", ApiSince=28, DoNotGenerateAcw=true)]
public sealed class ImageDecoder : Java.Lang.Object, IDisposable, Java.Interop.IJavaPeerable, Java.Lang.IAutoCloseable
[<Android.Runtime.Register("android/graphics/ImageDecoder", ApiSince=28, DoNotGenerateAcw=true)>]
type ImageDecoder = class
    inherit Object
    interface IAutoCloseable
    interface IJavaObject
    interface IDisposable
    interface IJavaPeerable
Inheritance
ImageDecoder
Attributes
Implements

Remarks

A class for converting encoded images (like PNG, JPEG, WEBP, GIF, or HEIF) into Drawable or Bitmap objects.

To use it, first create a Source Source using one of the createSource overloads. For example, to decode from a Uri, call #createSource(ContentResolver, Uri) and pass the result to #decodeDrawable(Source) or #decodeBitmap(Source):

File file = new File(...);
             ImageDecoder.Source source = ImageDecoder.createSource(file);
             Drawable drawable = ImageDecoder.decodeDrawable(source);

To change the default settings, pass the Source Source and an OnHeaderDecodedListener OnHeaderDecodedListener to #decodeDrawable(Source, OnHeaderDecodedListener) or #decodeBitmap(Source, OnHeaderDecodedListener). For example, to create a sampled image with half the width and height of the original image, call #setTargetSampleSize setTargetSampleSize(2) inside OnHeaderDecodedListener#onHeaderDecoded onHeaderDecoded:

OnHeaderDecodedListener listener = new OnHeaderDecodedListener() {
                 public void onHeaderDecoded(ImageDecoder decoder, ImageInfo info, Source source) {
                     decoder.setTargetSampleSize(2);
                 }
             };
             Drawable drawable = ImageDecoder.decodeDrawable(source, listener);

The ImageInfo ImageInfo contains information about the encoded image, like its width and height, and the Source Source can be used to match to a particular Source Source if a single OnHeaderDecodedListener OnHeaderDecodedListener is used with multiple Source Source objects.

The OnHeaderDecodedListener OnHeaderDecodedListener can also be implemented as a lambda:

Drawable drawable = ImageDecoder.decodeDrawable(source, (decoder, info, src) -&gt; {
                 decoder.setTargetSampleSize(2);
             });

If the encoded image is an animated GIF or WEBP, #decodeDrawable decodeDrawable will return an AnimatedImageDrawable. To start its animation, call AnimatedImageDrawable#start AnimatedImageDrawable.start():

Drawable drawable = ImageDecoder.decodeDrawable(source);
             if (drawable instanceof AnimatedImageDrawable) {
                 ((AnimatedImageDrawable) drawable).start();
             }

By default, a Bitmap created by ImageDecoder (including one that is inside a Drawable) will be immutable (i.e. Bitmap#isMutable Bitmap.isMutable() returns false), and it will typically have ConfigBitmap.Config#HARDWARE. Although these properties can be changed with #setMutableRequired setMutableRequired(true) (which is only compatible with #decodeBitmap(Source) and #decodeBitmap(Source, OnHeaderDecodedListener)) and #setAllocator, it is also possible to apply custom effects regardless of the mutability of the final returned object by passing a PostProcessor to #setPostProcessor setPostProcessor. A PostProcessor can also be a lambda:

Drawable drawable = ImageDecoder.decodeDrawable(source, (decoder, info, src) -&gt; {
                 decoder.setPostProcessor((canvas) -&gt; {
                         // This will create rounded corners.
                         Path path = new Path();
                         path.setFillType(Path.FillType.INVERSE_EVEN_ODD);
                         int width = canvas.getWidth();
                         int height = canvas.getHeight();
                         path.addRoundRect(0, 0, width, height, 20, 20, Path.Direction.CW);
                         Paint paint = new Paint();
                         paint.setAntiAlias(true);
                         paint.setColor(Color.TRANSPARENT);
                         paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
                         canvas.drawPath(path, paint);
                         return PixelFormat.TRANSLUCENT;
                 });
             });

If the encoded image is incomplete or contains an error, or if an Exception occurs during decoding, a DecodeException DecodeException will be thrown. In some cases, the ImageDecoder may have decoded part of the image. In order to display the partial image, an OnPartialImageListener OnPartialImageListener must be passed to #setOnPartialImageListener setOnPartialImageListener. For example:

Drawable drawable = ImageDecoder.decodeDrawable(source, (decoder, info, src) -&gt; {
                 decoder.setOnPartialImageListener((DecodeException e) -&gt; {
                         // Returning true indicates to create a Drawable or Bitmap even
                         // if the whole image could not be decoded. Any remaining lines
                         // will be blank.
                         return true;
                 });
             });

Java documentation for android.graphics.ImageDecoder.

Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.

Fields

AllocatorDefault
Obsolete.

Use the default allocation for the pixel memory.

AllocatorHardware
Obsolete.

Require a Bitmap.Config#HARDWAREBitmap.

AllocatorSharedMemory
Obsolete.

Use shared memory for the pixel memory.

AllocatorSoftware
Obsolete.

Use a software allocation for the pixel memory.

MemoryPolicyDefault
Obsolete.

Use the most natural Bitmap.Config for the internal Bitmap.

MemoryPolicyLowRam
Obsolete.

Save memory if possible by using a denser Bitmap.Config at the cost of some image quality.

Properties

Class

Returns the runtime class of this Object.

(Inherited from Object)
Crop

Return the cropping rectangle, if set. -or- Crop the output to subset of the (possibly) scaled image.

DecodeAsAlphaMaskEnabled

Return whether to treat single channel input as alpha. -or- Specify whether to potentially treat the output as an alpha mask.

Handle

The handle to the underlying Android instance.

(Inherited from Object)
JniIdentityHashCode (Inherited from Object)
JniPeerMembers
MemorySizePolicy

Retrieve the memory policy for the decoded Bitmap. -or- Specify the memory policy for the decoded Bitmap.

MutableRequired

Return whether the decoded Bitmap will be mutable. -or- Specify whether the Bitmap should be mutable.

OnPartialImageListener

Set (replace) the OnPartialImageListener on this object.

PeerReference (Inherited from Object)
PostProcessor

Return the PostProcessor currently set. -or- Modify the image after decoding and scaling.

ThresholdClass

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

(Inherited from Object)
ThresholdType

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

(Inherited from Object)
UnpremultipliedRequired

Return whether the Bitmap will have unpremultiplied pixels. -or- Specify whether the Bitmap should have unpremultiplied pixels.

Methods

Clone()

Creates and returns a copy of this object.

(Inherited from Object)
Close()

Closes this resource, relinquishing any underlying resources.

CreateSource(AssetManager, String)

Create a new Source from a android.net.Uri.

CreateSource(Byte[], Int32, Int32)

Create a new Source from a android.net.Uri.

CreateSource(Byte[])

Create a new Source from a android.net.Uri.

CreateSource(ByteBuffer)

Create a new Source from a android.net.Uri.

CreateSource(ContentResolver, Uri)

Create a new Source from a android.net.Uri.

CreateSource(File)

Create a new Source from a android.net.Uri.

CreateSource(ICallable)

Create a new Source from a android.net.Uri.

CreateSource(Resources, Int32)

Create a new Source from a android.net.Uri.

DecodeBitmap(ImageDecoder+Source, ImageDecoder+IOnHeaderDecodedListener)

See #decodeBitmap(Source, OnHeaderDecodedListener).

DecodeBitmap(ImageDecoder+Source)

See #decodeBitmap(Source, OnHeaderDecodedListener).

DecodeDrawable(ImageDecoder+Source, ImageDecoder+IOnHeaderDecodedListener)

See #decodeDrawable(Source, OnHeaderDecodedListener).

DecodeDrawable(ImageDecoder+Source)

See #decodeDrawable(Source, OnHeaderDecodedListener).

Dispose() (Inherited from Object)
Dispose(Boolean) (Inherited from Object)
Equals(Object)

Indicates whether some other object is "equal to" this one.

(Inherited from Object)
GetHashCode()

Returns a hash code value for the object.

(Inherited from Object)
IsMimeTypeSupported(String)

Return if the given MIME type is a supported file format that can be decoded by this class.

JavaFinalize()

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

(Inherited from Object)
Notify()

Wakes up a single thread that is waiting on this object's monitor.

(Inherited from Object)
NotifyAll()

Wakes up all threads that are waiting on this object's monitor.

(Inherited from Object)
SetHandle(IntPtr, JniHandleOwnership)

Sets the Handle property.

(Inherited from Object)
SetTargetColorSpace(ColorSpace)

Specify the desired ColorSpace for the output.

SetTargetSampleSize(Int32)

Set the target size with a sampleSize.

SetTargetSize(Int32, Int32)

Specify the size of the output Drawable or Bitmap.

ToArray<T>() (Inherited from Object)
ToString()

Returns a string representation of the object.

(Inherited from Object)
UnregisterFromRuntime() (Inherited from Object)
Wait()

Causes the current thread to wait until it is awakened, typically by being <em>notified</em> or <em>interrupted</em>.

(Inherited from Object)
Wait(Int64, Int32)

Causes the current thread to wait until it is awakened, typically by being <em>notified</em> or <em>interrupted</em>, or until a certain amount of real time has elapsed.

(Inherited from Object)
Wait(Int64)

Causes the current thread to wait until it is awakened, typically by being <em>notified</em> or <em>interrupted</em>, or until a certain amount of real time has elapsed.

(Inherited from Object)

Events

PartialImage

Explicit Interface Implementations

IJavaPeerable.Disposed() (Inherited from Object)
IJavaPeerable.DisposeUnlessReferenced() (Inherited from Object)
IJavaPeerable.Finalized() (Inherited from Object)
IJavaPeerable.JniManagedPeerState (Inherited from Object)
IJavaPeerable.SetJniIdentityHashCode(Int32) (Inherited from Object)
IJavaPeerable.SetJniManagedPeerState(JniManagedPeerStates) (Inherited from Object)
IJavaPeerable.SetPeerReference(JniObjectReference) (Inherited from Object)

Extension Methods

JavaCast<TResult>(IJavaObject)

Performs an Android runtime-checked type conversion.

JavaCast<TResult>(IJavaObject)
GetJniTypeName(IJavaPeerable)

Applies to