Class EncodedImage

java.lang.Object
com.codename1.ui.Image
com.codename1.ui.EncodedImage
All Implemented Interfaces:
ActionSource
Direct Known Subclasses:
ComponentImage.EncodedWrapper, FileEncodedImage, FileEncodedImageAsync, ReplaceableImage, StorageImage, StorageImageAsync, URLImage

public class EncodedImage extends Image

EncodedImage is the workhorse of Codename One. Images returned from resource files are EncodedImage and many API's expect it.

EncodedImage is effectively an image that is "hidden" and extracted as needed to remove the memory overhead associated with loaded image. When creating an EncodedImage only the PNG (or JPEG etc.) is loaded to an array in RAM. Normally, such images are very small (relatively) so they can be kept in memory without much overhead.

When image information is needed (pixels) the image is decoded into RAM and kept in a weak/sort reference (see com.codename1.ui.Display#createSoftWeakRef(java.lang.Object)). This allows the image to be cached for performance and allows the garbage collector to reclaim it when the memory becomes scarce.

Since the fully decoded image can be pretty big (width X height X 4) the ability to store just the encoded image can be pretty stark. E.g. A standard 50x100 image will take up 20,000 bytes of RAM for a standard image but an EncodedImage can reduce that to 1kb-2kb of RAM.

When drawing an EncodedImage it checks the weak reference cache and if the image is cached then it is shown otherwise the image is loaded the encoded image cache it then drawn.

EncodedImage is not final and can be derived to produce complex image fetching strategies e.g. the com.codename1.ui.URLImage class that can dynamically download its content from the web.

EncodedImage can be instantiated via the create methods in the class. Pretty much any image can be converted into an EncodedImage via the boolean) method.

EncodedImage Locking

Naturally loading the image is more expensive so we want the images that are on the current form to remain in cache (otherwise GC will thrash a lot). That's where #lock() kicks in, when #lock() is active we keep a hard reference to the actual native image so it won't get GC'd. This significantly improves performance!

Internally this is invoked automatically for background images, icons etc. which results in a huge performance boost. This makes sense since these images are currently showing and they will be in RAM anyway. However, if you use a complex renderer or custom drawing UI you should #lock() your images where possible!

To verify that locking might be a problem you can launch the performance monitor tool (accessible from the simulator menu), if you get log messages that indicate that an unlocked image was drawn you might have a problem.

  • Constructor Summary

    Constructors
    Modifier
    Constructor
    Description
    protected
    EncodedImage(int width, int height)
    Allows subclasses to create more advanced variations of this class that lazily store the data in an arbitrary location.
  • Method Summary

    Modifier and Type
    Method
    Description
    void
    asyncLock(Image internal)
    Async lock is the equivalent of a lock operation, however it uses the given image as the hard cache and performs the actual image loading asynchronously.
    create(byte[] data)
    Creates an image from the given byte array
    create(byte[] data, int width, int height, boolean opacity)
    Creates an image from the given byte array with the variables set appropriately.
    Creates an image from the input stream
    create(InputStream i, int size)
    Creates an image from the input stream, this version of the method is somewhat faster than the version that doesn't accept size
    Creates an image from the input stream
    createFromImage(Image i, boolean jpeg)
    Converts an image to encoded image
    static Image
    createFromRGB(int[] argb, int width, int height, boolean jpeg)
    Tries to create an encoded image from RGB which is more efficient, however if this fails it falls back to regular RGB image.
    createMulti(int[] dpis, byte[][] data)
    Creates an encoded image that acts as a multi-image, DO NOT USE THIS METHOD.
    protected void
    drawImage(Graphics g, Object nativeGraphics, int x, int y)
    Callback invoked internally by Codename One to draw the image/frame onto the display.
    protected void
    drawImage(Graphics g, Object nativeGraphics, int x, int y, int w, int h)
    Callback invoked internally by Codename One to draw the image/frame onto the display.
    If this is a mutable image a graphics object allowing us to draw on it is returned.
    int
    Returns the height of the image
    Returns the platform specific image implementation, warning the implementation class can change between revisions of Codename One and platforms.
    byte[]
    Returns the byte array data backing the image allowing the image to be stored and discarded completely from RAM.
    protected Image
    Returns the actual image represented by the encoded image, this image will be cached in a weak/soft reference internally.
    int
    Returns the width of the image
    boolean
    Returns true if this is an animated image
    boolean
    Returns true if the image is locked
    boolean
    Indicates whether this image is opaque or not
    void
    This callback indicates that a component pointing at this image is initialized, this allows an image to make performance sensitive considerations e.g.
    modifyAlpha(byte alpha)
    Creates a new image instance with the alpha channel of opaque/translucent pixels within the image using the new alpha value.
    modifyAlpha(byte alpha, int removeColor)
    Creates a new image instance with the alpha channel of opaque/translucent pixels within the image using the new alpha value.
    protected void
    A subclass might choose to load asynchroniously and reset the cache when the image is ready.
    rotate(int degrees)
    Returns an instance of this image rotated by the given number of degrees.
    void
    scale(int width, int height)
    Scale the image to the given width and height, this is a fast algorithm that preserves translucent information
    scaled(int width, int height)
    Returns a scaled version of this image image using the given width and height, this is a fast algorithm that preserves translucent information.
    scaledEncoded(int width, int height)
    Performs scaling using ImageIO to generate an encoded Image
    scaledHeight(int height)
    Scales the image to the given height while updating the width based on the aspect ratio of the height
    scaledSmallerRatio(int width, int height)
    Scales the image while maintaining the aspect ratio to the smaller size image
    scaledWidth(int width)
    Scales the image to the given width while updating the height based on the aspect ratio of the width
    subImage(int x, int y, int width, int height, boolean processAlpha)
    Extracts a subimage from the given image allowing us to breakdown a single large image into multiple smaller images in RAM, this actually creates a standalone version of the image for use.
    void
    toRGB(RGBImage image, int destX, int destY, int x, int y, int width, int height)
    Extracts data from this image into the given RGBImage
    void
    This callback indicates that a component pointing at this image is now deinitilized This method may be invoked multiple times.

    Methods inherited from class Image

    addActionListener, animate, applyMask, applyMask, applyMaskAutoScale, createImage, createImage, createImage, createImage, createImage, createImage, createImage, createIndexed, createMask, createSVG, dispose, exifRotation, exifRotation, exifRotation, fill, fireChangedEvent, flipHorizontally, flipVertically, getExifOrientationTag, getExifOrientationTag, getImageName, getRGB, getRGB, getRGBCached, getSVGDocument, isAlphaMutableImageSupported, isJPEG, isPNG, isSVG, isSVGSupported, mirror, modifyAlphaWithTranslucency, removeActionListener, requiresDrawImage, rotate180Degrees, rotate270Degrees, rotate90Degrees, scaledLargerRatio, setImageName
    Modifier and Type
    Method
    Description
    void
    Adds ActionListener to receive action events form this source.
    boolean
    Advances this image's animation state, if it is animated.
    Applies the given alpha mask onto this image and returns the resulting image see the createMask method for indication on how to convert an image into an alpha mask.
    applyMask(Object mask, int x, int y)
    Applies the given alpha mask onto this image and returns the resulting image see the createMask method for indication on how to convert an image into an alpha mask.
    Applies the given alpha mask onto this image and returns the resulting image see the createMask method for indication on how to convert an image into an alpha mask.
    static Image
    createImage(byte[] bytes, int offset, int len)
    creates an image from a given byte array data
    static Image
    createImage(int[] rgb, int width, int height)
    creates an image from an RGB image
    static Image
    createImage(int width, int height)
    Creates a white opaque mutable image that may be manipulated using #getGraphics().
    static Image
    createImage(int width, int height, int fillColor)
    Creates a mutable image that may be manipulated using #getGraphics().
    static Image
    creates an image from an InputStream
    static Image
    createImage(Object nativeImage)
    creates an image from the given native image (e.g. MIDP image object)
    static Image
    Creates an image from a path.
    static Image
    createIndexed(int width, int height, int[] palette, byte[] data)
    Creates an indexed image with byte data this method may return a native indexed image rather than an instance of the IndexedImage class
    Creates a mask from the given image, a mask can be used to apply an arbitrary alpha channel to any image.
    static Image
    createSVG(String baseURL, boolean animated, byte[] data)
    Creates an SVG Image from the given byte array data and the base URL, this method will throw an exception if SVG is unsupported.
    void
    DO NOT CALL THIS METHOD UNLESS YOU KNOW WHAT YOU ARE DOING, IT WILL CAUSE PLATFORM SPECIFC CRASHES OTHERWISE! Images dispose automatically for most cases except for very rare special cases.
    static Image
    exifRotation(String capturedImage)
    The main use case of this method is the automatic rotation and flipping of an image returned from the camera or from the gallery, preserving the original format (jpeg or png); it detects the Exif Orientation Tag, if available (all the possible Exif Orientation Tag values are supported); transparency is not preserved.
    static Image
    exifRotation(String capturedImage, String rotatedImage)
    The main use case of this method is the automatic rotation and flipping of an image returned from the camera or from the gallery, preserving the original format (jpeg or png); it detects the Exif Orientation Tag, if available (all the possible Exif Orientation Tag values are supported); transparency is not preserved.
    static Image
    exifRotation(String capturedImage, String rotatedImage, int maxSize)
    The main use case of this method is the automatic rotation and flipping of an image returned from the camera or from the gallery, preserving the original format (jpeg or png); it detects the Exif Orientation Tag, if available (all the possible Exif Orientation Tag values are supported); transparency is not preserved.
    fill(int width, int height)
    Resizes/crops the image so that its center fills the given dimensions.
    void
     
    flipHorizontally(boolean maintainOpacity)
    Flips this image on the horizontal axis
    flipVertically(boolean maintainOpacity)
    Flips this image on the vertical axis
    static int
    Gets the EXIF orientation tag of an image, if it's available.
    static int
    Gets the EXIF orientation tag of an image if it's available.
    The name of the image is set for some images mostly to ease the debugging of Codename One application
    int[]
    Returns the content of this image as a newly created ARGB array.
    void
    getRGB(int[] rgbData)
    Returns the content of this image in the supplied ARGB array.
    int[]
    Returns the content of this image as a newly created ARGB array or a cached instance if possible.
    Returns a platform specific DOM object that can be manipulated by the user to change the SVG Image
    static boolean
    Returns true if mutable images support alpha transparency
    static boolean
    isJPEG(InputStream inputStream)
    Very fast method to detect if the given inputStream is a JPEG image (according to its guessed mime type)
    static boolean
    isPNG(InputStream inputStream)
    Very fast method to detect if the given inputStream is a PNG image (according to its guessed mime type)
    boolean
    Indicates if this image represents an SVG file or a bitmap file
    static boolean
    Indicates whether the underlying platform supports creating an SVG Image
    Creates a mirror image for the given image which is useful for some RTL scenarios.
    Creates a new image instance with the alpha channel of opaque pixels within the image using the new alpha value.
    void
    Removes ActionListener so that it will no longer receive events from this source.
    boolean
    New label optimizations don't invoke drawImage and instead just pass the native image directly to the underlying renderer.
    rotate180Degrees(boolean maintainOpacity)
    Rotates the image by 180 degrees
    rotate270Degrees(boolean maintainOpacity)
    Rotates the image by 270 degrees while changing the ratio of the picture
    rotate90Degrees(boolean maintainOpacity)
    Rotates this image by 90 degrees while changing the ratio of the picture
    scaledLargerRatio(int width, int height)
    Scales the image while maintaining the aspect ratio to the larger size image
    void
    setImageName(String imageName)
    The name of the image is set for some images mostly to ease the debugging of Codename One application

    Methods inherited from class Object

    clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    Modifier and Type
    Method
    Description
    protected Object
     
    boolean
    Indicates whether some other object is "equal to" this one.
    final Class
    Returns the runtime class of an object.
    int
    Returns a hash code value for the object.
    final void
    Wakes up a single thread that is waiting on this object's monitor.
    final void
    Wakes up all threads that are waiting on this object's monitor.
    Returns a string representation of the object.
    final void
    Causes current thread to wait until another thread invokes the method or the method for this object.
    final void
    wait(long timeout)
    Causes current thread to wait until either another thread invokes the method or the method for this object, or a specified amount of time has elapsed.
    final void
    wait(long timeout, int nanos)
    Causes current thread to wait until another thread invokes the method or the method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.
  • Constructor Details

    • EncodedImage

      protected EncodedImage(int width, int height)

      Allows subclasses to create more advanced variations of this class that lazily store the data in an arbitrary location.

      Parameters
      • width: -1 if unknown ideally the width/height should be known in advance

      • height: -1 if unknown ideally the width/height should be known in advance

  • Method Details

    • createMulti

      public static EncodedImage createMulti(int[] dpis, byte[][] data)

      Creates an encoded image that acts as a multi-image, DO NOT USE THIS METHOD. Its for internal use to improve the user experience of the simulator

      Parameters
      • dpis: device DPI's

      • data: the data matching each multi-image DPI

      Returns

      an encoded image that acts as a multi-image in runtime

      Deprecated
    • createFromImage

      public static EncodedImage createFromImage(Image i, boolean jpeg)

      Converts an image to encoded image

      Parameters
      • i: image

      • jpeg: true to try and set jpeg, will do a best effort but this isn't guaranteed

      Returns

      an encoded image or null

    • createFromRGB

      public static Image createFromRGB(int[] argb, int width, int height, boolean jpeg)

      Tries to create an encoded image from RGB which is more efficient, however if this fails it falls back to regular RGB image. This method is slower than creating an RGB image (not to be confused with the RGBImage class which is something ENTIRELY different!).

      Parameters
      • argb: an argb array

      • width: the width for the image

      • height: the height for the image

      • jpeg: uses jpeg format internally which is opaque and could be faster/smaller

      Returns

      an image which we hope is an encoded image

    • create

      public static EncodedImage create(byte[] data)

      Creates an image from the given byte array

      Parameters
      • data: the data of the image
      Returns

      newly created encoded image

    • create

      public static EncodedImage create(byte[] data, int width, int height, boolean opacity)

      Creates an image from the given byte array with the variables set appropriately. This saves LWUIT allot of resources since it doesn't need to actually traverse the pixels of an image to find out details about it.

      Parameters
      • data: the data of the image

      • width: the width of the image

      • height: the height of the image

      • opacity: true for an opaque image

      Returns

      newly created encoded image

    • create

      public static EncodedImage create(InputStream i) throws IOException

      Creates an image from the input stream

      Parameters
      • i: the input stream
      Returns

      newly created encoded image

      Throws
      • java.io.IOException: if thrown by the input stream
      Throws:
      IOException
    • create

      public static EncodedImage create(InputStream i, int size) throws IOException

      Creates an image from the input stream, this version of the method is somewhat faster than the version that doesn't accept size

      Parameters
      • i: the input stream

      • size: the size of the stream

      Returns

      newly created encoded image

      Throws
      • java.io.IOException: if thrown by the input stream
      Throws:
      IOException
    • create

      public static EncodedImage create(String i) throws IOException

      Creates an image from the input stream

      Parameters
      • i: the resource
      Returns

      newly created encoded image

      Throws
      • java.io.IOException: if thrown by the input stream
      Throws:
      IOException
    • resetCache

      protected void resetCache()
      A subclass might choose to load asynchroniously and reset the cache when the image is ready.
    • getImageData

      public byte[] getImageData()

      Returns the byte array data backing the image allowing the image to be stored and discarded completely from RAM.

      Returns

      byte array used to create the image, e.g. encoded PNG, JPEG etc.

    • getImage

      public Object getImage()

      Returns the platform specific image implementation, warning the implementation class can change between revisions of Codename One and platforms.

      Returns

      platform specific native implementation for this image object

      Overrides:
      getImage in class Image
    • getInternal

      protected Image getInternal()

      Returns the actual image represented by the encoded image, this image will be cached in a weak/soft reference internally. This method is useful to detect when the system actually created an image instance. You shouldn't invoke this method manually!

      Returns

      drawable image instance

    • isLocked

      public boolean isLocked()

      Returns true if the image is locked

      Returns

      false by default

      Overrides:
      isLocked in class Image
    • asyncLock

      public void asyncLock(Image internal)

      Async lock is the equivalent of a lock operation, however it uses the given image as the hard cache and performs the actual image loading asynchronously. On completion this method will invoke repaint on the main form if applicable.

      Parameters
      • internal: the image to show while the actual image loads.
      Overrides:
      asyncLock in class Image
    • lock

      public void lock()
      This callback indicates that a component pointing at this image is initialized, this allows an image to make performance sensitive considerations e.g. an encoded image might choose to cache itself in RAM. This method may be invoked multiple times.
      Overrides:
      lock in class Image
    • unlock

      public void unlock()
      This callback indicates that a component pointing at this image is now deinitilized This method may be invoked multiple times.
      Overrides:
      unlock in class Image
    • subImage

      public Image subImage(int x, int y, int width, int height, boolean processAlpha)

      Extracts a subimage from the given image allowing us to breakdown a single large image into multiple smaller images in RAM, this actually creates a standalone version of the image for use.

      Parameters
      • x: the x offset from the image

      • y: the y offset from the image

      • width: the width of internal images

      • height: the height of internal images

      • processAlpha: whether alpha should be processed as well as part of the cutting

      Returns

      An array of all the possible images that can be created from the source

      Overrides:
      subImage in class Image
    • rotate

      public Image rotate(int degrees)

      Returns an instance of this image rotated by the given number of degrees. By default 90 degree angle divisions are supported, anything else is implementation dependent. This method assumes a square image. Notice that it is inefficient in the current implementation to rotate to non-square angles,

      E.g. rotating an image to 45, 90 and 135 degrees is inefficient. Use rotatate to 45, 90 and then rotate the 45 to another 90 degrees to achieve the same effect with less memory.

      Parameters
      • degrees: A degree in right angle must be larger than 0 and up to 359 degrees
      Returns

      new image instance with the closest possible rotation

      Overrides:
      rotate in class Image
    • modifyAlpha

      public Image modifyAlpha(byte alpha)

      Creates a new image instance with the alpha channel of opaque/translucent pixels within the image using the new alpha value. Transparent (alpha == 0) pixels remain transparent. All other pixels will have the new alpha value.

      Parameters
      • alpha: New value for the entire alpha channel
      Returns
      Overrides:
      modifyAlpha in class Image
      Returns:
      Translucent/Opaque image based on the alpha value and the pixels of this image
    • modifyAlpha

      public Image modifyAlpha(byte alpha, int removeColor)

      Creates a new image instance with the alpha channel of opaque/translucent pixels within the image using the new alpha value. Transparent (alpha == 0) pixels remain transparent. All other pixels will have the new alpha value.

      Parameters
      • alpha: New value for the entire alpha channel

      • removeColor: pixels matching this color are made transparent (alpha channel ignored)

      Returns
      Overrides:
      modifyAlpha in class Image
      Returns:
      Translucent/Opaque image based on the alpha value and the pixels of this image
    • getGraphics

      public Graphics getGraphics()

      If this is a mutable image a graphics object allowing us to draw on it is returned.

      Returns

      Graphics object allowing us to manipulate the content of a mutable image

      Overrides:
      getGraphics in class Image
    • getWidth

      public int getWidth()

      Returns the width of the image

      Returns

      the width of the image

      Overrides:
      getWidth in class Image
    • getHeight

      public int getHeight()

      Returns the height of the image

      Returns

      the height of the image

      Overrides:
      getHeight in class Image
    • drawImage

      protected void drawImage(Graphics g, Object nativeGraphics, int x, int y)

      Callback invoked internally by Codename One to draw the image/frame onto the display. Image subclasses can override this method to perform drawing of custom image types.

      Parameters
      • g: the graphics object

      • nativeGraphics: the underlying native graphics which might be essential for some image types

      • x: the x coordinate

      • y: the y coordinate

      Overrides:
      drawImage in class Image
    • drawImage

      protected void drawImage(Graphics g, Object nativeGraphics, int x, int y, int w, int h)

      Callback invoked internally by Codename One to draw the image/frame onto the display. Image subclasses can override this method to perform drawing of custom image types.

      Parameters
      • g: the graphics object

      • nativeGraphics: the underlying native graphics which might be essential for some image types

      • x: the x coordinate

      • y: the y coordinate

      • w: the width to occupy

      • h: the height to occupy

      Overrides:
      drawImage in class Image
    • toRGB

      public void toRGB(RGBImage image, int destX, int destY, int x, int y, int width, int height)

      Extracts data from this image into the given RGBImage

      Parameters
      • image: RGBImage that would receive pixel data

      • destX: @param destX x location within RGBImage into which the data will be written

      • destY: @param destY y location within RGBImage into which the data will be written

      • x: location within the source image

      • y: location within the source image

      • width: size of the image to extract from the source image

      • height: size of the image to extract from the source image

      Overrides:
      toRGB in class Image
    • scaledWidth

      public Image scaledWidth(int width)

      Scales the image to the given width while updating the height based on the aspect ratio of the width

      Parameters
      • width: the given new image width
      Returns

      the newly created image

      Overrides:
      scaledWidth in class Image
    • scaledHeight

      public Image scaledHeight(int height)

      Scales the image to the given height while updating the width based on the aspect ratio of the height

      Parameters
      • height: the given new image height
      Returns

      the newly created image

      Overrides:
      scaledHeight in class Image
    • scaledSmallerRatio

      public Image scaledSmallerRatio(int width, int height)

      Scales the image while maintaining the aspect ratio to the smaller size image

      Parameters
      • width: the given new image width

      • height: the given new image height

      Returns

      the newly created image

      Overrides:
      scaledSmallerRatio in class Image
    • scaledEncoded

      public EncodedImage scaledEncoded(int width, int height)

      Performs scaling using ImageIO to generate an encoded Image

      Parameters
      • width: the width of the image, -1 to scale based on height and preserve aspect ratio

      • height: the height of the image, -1 to scale based on width and preserve aspect ratio

      Returns

      new encoded image

    • scaled

      public Image scaled(int width, int height)

      Returns a scaled version of this image image using the given width and height, this is a fast algorithm that preserves translucent information. The method accepts -1 to preserve aspect ratio in the given axis.

      Parameters
      • width: width for the scaling

      • height: height of the scaled image

      Returns

      new image instance scaled to the given height and width

      Overrides:
      scaled in class Image
    • scale

      public void scale(int width, int height)

      Scale the image to the given width and height, this is a fast algorithm that preserves translucent information

      Parameters
      • width: width for the scaling

      • height: height of the scaled image

      Deprecated
      Overrides:
      scale in class Image
    • isAnimation

      public boolean isAnimation()

      Returns true if this is an animated image

      Returns

      true if this image represents an animation

      Overrides:
      isAnimation in class Image
    • isOpaque

      public boolean isOpaque()

      Indicates whether this image is opaque or not

      Returns

      true if the image is completely opqaque which allows for some heavy optimizations

      Overrides:
      isOpaque in class Image