Class URLImage

All Implemented Interfaces:
ActionSource

public final class URLImage extends EncodedImage

URLImage allows us to create an image from a URL. If the image was downloaded already it is fetched from cache; if not it is downloaded optionally scaled/adapted and placed in cache.

By default an image is fetched lazily as it is asked for by the GUI unless the fetch() method is invoked in which case the IO code is executed immediately.

This sample code show a URLImage that is fetched to the title area background and scaled/cropped to fit device specific dimensions.

Toolbar.setGlobalToolbar(true);

Form hi = new Form("Toolbar", new BoxLayout(BoxLayout.Y_AXIS));
EncodedImage placeholder = EncodedImage.createFromImage(Image.createImage(hi.getWidth(), hi.getWidth() / 5, 0xffff0000), true);
URLImage background = URLImage.createToStorage(placeholder, "400px-AGameOfThrones.jpg",
        "http://awoiaf.westeros.org/images/thumb/9/93/AGameOfThrones.jpg/400px-AGameOfThrones.jpg");
background.fetch();
Style stitle = hi.getToolbar().getTitleComponent().getUnselectedStyle();
stitle.setBgImage(background);
stitle.setBackgroundType(Style.BACKGROUND_IMAGE_SCALED_FILL);
stitle.setPaddingUnit(Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS);
stitle.setPaddingTop(15);
SpanButton credit = new SpanButton("This excerpt is from A Wiki Of Ice And Fire. Please check it out by clicking here!");
credit.addActionListener((e) -> Display.getInstance().execute("http://awoiaf.westeros.org/index.php/A_Game_of_Thrones"));
hi.add(new SpanLabel("A Game of Thrones is the first of seven planned novels in A Song of Ice and Fire, an epic fantasy series by American author George R. R. Martin. It was first published on 6 August 1996. The novel was nominated for the 1998 Nebula Award and the 1997 World Fantasy Award,[1] and won the 1997 Locus Award.[2] The novella Blood of the Dragon, comprising the Daenerys Targaryen chapters from the novel, won the 1997 Hugo Award for Best Novella. ")).
        add(new Label("Plot introduction", "Heading")).
        add(new SpanLabel("A Game of Thrones is set in the Seven Kingdoms of Westeros, a land reminiscent of Medieval Europe. In Westeros the seasons last for years, sometimes decades, at a time.\n\n" +
            "Fifteen years prior to the novel, the Seven Kingdoms were torn apart by a civil war, known alternately as \"Robert's Rebellion\" and the \"War of the Usurper.\" Prince Rhaegar Targaryen kidnapped Lyanna Stark, arousing the ire of her family and of her betrothed, Lord Robert Baratheon (the war's titular rebel). The Mad King, Aerys II Targaryen, had Lyanna's father and eldest brother executed when they demanded her safe return. Her second brother, Eddard, joined his boyhood friend Robert Baratheon and Jon Arryn, with whom they had been fostered as children, in declaring war against the ruling Targaryen dynasty, securing the allegiances of House Tully and House Arryn through a network of dynastic marriages (Lord Eddard to Catelyn Tully and Lord Arryn to Lysa Tully). The powerful House Tyrell continued to support the King, but House Lannister and House Martell both stalled due to insults against their houses by the Targaryens. The civil war climaxed with the Battle of the Trident, when Prince Rhaegar was killed in battle by Robert Baratheon. The Lannisters finally agreed to support King Aerys, but then brutally... ")).
        add(credit);

ComponentAnimation title = hi.getToolbar().getTitleComponent().createStyleAnimation("Title", 200);
hi.getAnimationManager().onTitleScrollAnimation(title);
hi.show();

This sample code shows the usage of the nestoria API to fill out an infinitely scrolling list in it we use URLImage to fetch the icon.

Form hi = new Form("InfiniteScrollAdapter", BoxLayout.y());

Style s = UIManager.getInstance().getComponentStyle("MultiLine1");
FontImage p = FontImage.createMaterial(FontImage.MATERIAL_PORTRAIT, s);
EncodedImage placeholder = EncodedImage.createFromImage(
        p.scaled(p.getWidth() * 3, p.getHeight() * 3),
        false);

InfiniteScrollAdapter.createInfiniteScroll(hi.getContentPane(), () -> {
    MultiButton[] cmps = new MultiButton[10];
    for (int i = 0; i < cmps.length; i++) {
        String imageKey = "listing-" + i;
        String imageUrl = "https://example.com/images/" + i + ".png";
        MultiButton row = new MultiButton("Listing " + i);
        row.setIcon(URLImage.createToStorage(placeholder, imageKey, imageUrl));
        cmps[i] = row;
    }
    InfiniteScrollAdapter.addMoreComponents(hi.getContentPane(), cmps, true);
}, true);
hi.show();

You can use adapters with masks using syntax similar to this to create a round image mask for a URLImage:

Image roundMask = Image.createImage(placeholder.getWidth(), placeholder.getHeight(), 0xff000000);
Graphics gr = roundMask.getGraphics();
gr.setColor(0xffffff);
gr.fillArc(0, 0, placeholder.getWidth(), placeholder.getHeight(), 0, 360);

URLImage.ImageAdapter ada = URLImage.createMaskAdapter(roundMask);
Image i = URLImage.createToStorage(placeholder, "fileNameInStorage", "http://xxx/myurl.jpg", ada);
  • Nested Class Summary

    Nested Classes
    Modifier and Type
    Class
    Description
    static interface 
    Invoked in a case of an error
    static interface 
    Allows applying resize logic to downloaded images you can use constant resize behaviors defined in this class.
  • Field Summary

    Fields
    Modifier and Type
    Field
    Description
    static final int
    Flag used by java.lang.String, com.codename1.ui.Image, int).
    static final int
    Flag used by java.lang.String, com.codename1.ui.Image, int) Equivalent to #RESIZE_SCALE.
    static final int
    Flag used by java.lang.String, com.codename1.ui.Image, int).
    Will fail if the downloaded image has a different size from the placeholder image
    Scales the image to match the size of the new image exactly
    Scales the image to match to fill the area while preserving aspect ratio
  • Method Summary

    Modifier and Type
    Method
    Description
    boolean
    Advances this image's animation state, if it is animated.
    static Image
    createCachedImage(String imageName, String url, Image placeholder, int resizeRule)
    Creates an image that will be downloaded on the fly as necessary.
    Creates an adapter that uses an image as a Mask, this is roughly the same as SCALE_TO_FILL with the exception that a mask will be applied later on.
     
    static URLImage
    Creates an image the will be downloaded on the fly as necessary
    static URLImage
    createToStorage(EncodedImage placeholder, String storageFile, String url)
    Creates an image the will be downloaded on the fly as necessary with RESIZE_SCALE_TO_FILL as the default behavior
    static URLImage
    createToStorage(EncodedImage placeholder, String storageFile, String url, URLImage.ImageAdapter adapter)
    Creates an image the will be downloaded on the fly as necessary
    void
    Images are normally fetched from storage or network only as needed, however if the download must start before the image is drawn this method can be invoked.
    The exception handler is used for callbacks in case of an error
    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.
    boolean
    Returns true if this is an animated image
    void
    Block this method from external callers as it might break the functionality
    boolean
    New label optimizations don't invoke drawImage and instead just pass the native image directly to the underlying renderer.
    static void
    The exception handler is used for callbacks in case of an error
    void
    Block this method from external callers as it might break the functionality

    Methods inherited from class EncodedImage

    asyncLock, create, create, create, create, create, createFromImage, createFromRGB, createMulti, drawImage, drawImage, getGraphics, getHeight, getImage, getWidth, isLocked, isOpaque, modifyAlpha, modifyAlpha, resetCache, rotate, scale, scaled, scaledEncoded, scaledHeight, scaledSmallerRatio, scaledWidth, subImage, toRGB
    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.
    int
    Returns the width of the image
    boolean
    Returns true if the image is locked
    boolean
    Indicates whether this image is opaque or not
    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

    Methods inherited from class Image

    addActionListener, 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, rotate180Degrees, rotate270Degrees, rotate90Degrees, scaledLargerRatio, setImageName
    Modifier and Type
    Method
    Description
    void
    Adds ActionListener to receive action events form this source.
    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.
    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.
  • Field Details

    • FLAG_RESIZE_FAIL

      public static final int FLAG_RESIZE_FAIL
      Flag used by java.lang.String, com.codename1.ui.Image, int). Equivalent to #RESIZE_FAIL
      See Also:
    • RESIZE_FAIL

      public static final URLImage.ImageAdapter RESIZE_FAIL
      Will fail if the downloaded image has a different size from the placeholder image
    • FLAG_RESIZE_SCALE

      public static final int FLAG_RESIZE_SCALE
      Flag used by java.lang.String, com.codename1.ui.Image, int) Equivalent to #RESIZE_SCALE.
      See Also:
    • RESIZE_SCALE

      public static final URLImage.ImageAdapter RESIZE_SCALE
      Scales the image to match the size of the new image exactly
    • FLAG_RESIZE_SCALE_TO_FILL

      public static final int FLAG_RESIZE_SCALE_TO_FILL
      Flag used by java.lang.String, com.codename1.ui.Image, int). Equivalent to #RESIZE_SCALE_TO_FILL.
      See Also:
    • RESIZE_SCALE_TO_FILL

      public static final URLImage.ImageAdapter RESIZE_SCALE_TO_FILL
      Scales the image to match to fill the area while preserving aspect ratio
  • Method Details

    • getExceptionHandler

      public static URLImage.ErrorCallback getExceptionHandler()

      The exception handler is used for callbacks in case of an error

      Returns

      the exceptionHandler

    • setExceptionHandler

      public static void setExceptionHandler(URLImage.ErrorCallback aExceptionHandler)

      The exception handler is used for callbacks in case of an error

      Parameters
      • aExceptionHandler: the exceptionHandler to set
    • createMaskAdapter

      public static URLImage.ImageAdapter createMaskAdapter(Image imageMask)

      Creates an adapter that uses an image as a Mask, this is roughly the same as SCALE_TO_FILL with the exception that a mask will be applied later on. This adapter requires that the resulting image be in the size of the imageMask!

      See the sample usage code below that implements a circular image masked downloader:

      Image roundMask = Image.createImage(placeholder.getWidth(), placeholder.getHeight(), 0xff000000);
      Graphics gr = roundMask.getGraphics();
      gr.setColor(0xffffff);
      gr.fillArc(0, 0, placeholder.getWidth(), placeholder.getHeight(), 0, 360);
      
      URLImage.ImageAdapter ada = URLImage.createMaskAdapter(roundMask);
      Image i = URLImage.createToStorage(placeholder, "fileNameInStorage", "http://xxx/myurl.jpg", ada);
      
      Parameters
      • imageMask: @param imageMask the mask image see the createMask() method of image for details of what a mask is, it will be used as the reference size for the image and resulting images must be of the same size!
      Returns

      the adapter

    • createMaskAdapter

      public static URLImage.ImageAdapter createMaskAdapter(Object mask)
    • createToStorage

      public static URLImage createToStorage(EncodedImage placeholder, String storageFile, String url)

      Creates an image the will be downloaded on the fly as necessary with RESIZE_SCALE_TO_FILL as the default behavior

      Parameters
      • placeholder: @param placeholder the image placeholder is shown as the image is loading/downloading and serves as the guideline to the size of the downloaded image.

      • storageFile: the file in storage to which the image will be stored

      • url: the url from which the image is fetched

      Returns

      a URLImage that will initialy just delegate to the placeholder

    • createToStorage

      public static URLImage createToStorage(EncodedImage placeholder, String storageFile, String url, URLImage.ImageAdapter adapter)

      Creates an image the will be downloaded on the fly as necessary

      Parameters
      • placeholder: @param placeholder the image placeholder is shown as the image is loading/downloading and serves as the guideline to the size of the downloaded image.

      • storageFile: the file in storage to which the image will be stored

      • url: the url from which the image is fetched

      • adapter: @param adapter the adapter used to adapt the image into place, it should scale the image if necessary

      Returns

      a URLImage that will initialy just delegate to the placeholder

    • createToFileSystem

      public static URLImage createToFileSystem(EncodedImage placeholder, String file, String url, URLImage.ImageAdapter adapter)

      Creates an image the will be downloaded on the fly as necessary

      Parameters
      • placeholder: @param placeholder the image placeholder is shown as the image is loading/downloading and serves as the guideline to the size of the downloaded image.

      • file: the file in the file system to which the image will be stored

      • url: the url from which the image is fetched

      • adapter: @param adapter the adapter used to adapt the image into place, it should scale the image if necessary

      Returns

      a URLImage that will initialy just delegate to the placeholder

    • createCachedImage

      public static Image createCachedImage(String imageName, String url, Image placeholder, int resizeRule)

      Creates an image that will be downloaded on the fly as necessary. On platforms that support a native image cache (e.g. Javascript), the image will be loaded directly from the native cache (i.e. it defers to the platform to handle all caching considerations. On platforms that don't have a native image cache but do have a caches directory FileSystemStorage#hasCachesDir(), this will call java.lang.String, java.lang.String, com.codename1.ui.URLImage.ImageAdapter) with a file location in the caches directory. In all other cases, this will call java.lang.String, java.lang.String).

      Parameters
      • imageName: The name of the image.

      • url: the URL from which the image is fetched

      • placeholder: @param placeholder the image placeholder is shown as the image is loading/downloading and serves as the guideline to the size of the downloaded image.

      • resizeRule: One of #FLAG_RESIZE_FAIL, #FLAG_RESIZE_SCALE, or #FLAG_RESIZE_SCALE_TO_FILL.

      Returns

      a Image that will initially just delegate to the placeholder

    • fetch

      public void fetch()
      Images are normally fetched from storage or network only as needed, however if the download must start before the image is drawn this method can be invoked. Notice that "immediately" doesn't mean synchronously, it just means that the image will be added to the queue right away but probably won't be available by the time the method completes.
    • 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

      Overrides:
      getInternal in class EncodedImage
    • requiresDrawImage

      public boolean requiresDrawImage()
      Description copied from class: Image

      New label optimizations don't invoke drawImage and instead just pass the native image directly to the underlying renderer. This is problematic for some image types specifically timeline & FontImage and this method allows these classes to indicate that they need that legacy behavior of calling drawImage.

      Returns

      true if a drawImage call is a required

      Overrides:
      requiresDrawImage in class Image
    • 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.

      Overrides:
      getImageData in class EncodedImage
    • animate

      public boolean animate()

      Advances this image's animation state, if it is animated.

      Returns

      true if the animation state changed.

      Overrides:
      animate in class Image
    • lock

      public void lock()
      Block this method from external callers as it might break the functionality
      Overrides:
      lock in class EncodedImage
    • unlock

      public void unlock()
      Block this method from external callers as it might break the functionality
      Overrides:
      unlock in class EncodedImage
    • isAnimation

      public boolean isAnimation()

      Returns true if this is an animated image

      Returns

      true if this image represents an animation

      Overrides:
      isAnimation in class EncodedImage