Class Image

java.lang.Object
com.codename1.ui.Image
All Implemented Interfaces:
ActionSource
Direct Known Subclasses:
ComponentImage, DynamicImage, EncodedImage, FontImage, RGBImage, Timeline

public class Image extends Object implements ActionSource
Abstracts the underlying platform images allowing us to treat them as a uniform object.
  • Constructor Summary

    Constructors
    Modifier
    Constructor
    Description
    protected
    Image(Object image)
    Subclasses may use this and point to an underlying native image which might be null for a case of an image that doesn't use native drawing
  • Method Summary

    Modifier and Type
    Method
    Description
    void
    Adds ActionListener to receive action events form this source.
    boolean
    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.
    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.
    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.
    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.
    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.
    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.
    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
    int
    Returns the width of the image
    static boolean
    Returns true if mutable images support alpha transparency
    boolean
    Returns true if this is an animated image
    static boolean
    isJPEG(InputStream inputStream)
    Very fast method to detect if the given inputStream is a JPEG image (according to its guessed mime type)
    boolean
    Returns true if the image is locked
    boolean
    Indicates whether this image is opaque or not
    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
    void
    This callback indicates that a component pointing at this image is initialized, this allows an image to make performance sensitive considerations e.g.
    Creates a mirror image for the given image which is useful for some RTL scenarios.
    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.
    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.
    rotate(int degrees)
    Returns an instance of this image rotated by the given number of degrees.
    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
    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.
    scaledHeight(int height)
    Scales the image to the given height while updating the width based on the aspect ratio of the height
    scaledLargerRatio(int width, int height)
    Scales the image while maintaining the aspect ratio to the larger size image
    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
    void
    setImageName(String imageName)
    The name of the image is set for some images mostly to ease the debugging of Codename One application
    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 Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Constructor Details

    • Image

      protected Image(Object image)

      Subclasses may use this and point to an underlying native image which might be null for a case of an image that doesn't use native drawing

      Parameters
      • image: native image object passed to the Codename One implementation
  • Method Details

    • isSVGSupported

      public static boolean isSVGSupported()

      Indicates whether the underlying platform supports creating an SVG Image

      Returns
      Returns:
      true if the method create SVG image would return a valid image object from an SVG Input stream
    • createSVG

      public static Image createSVG(String baseURL, boolean animated, byte[] data) throws IOException

      Creates an SVG Image from the given byte array data and the base URL, this method will throw an exception if SVG is unsupported.

      Parameters
      • baseURL: URL which is used to resolve relative references within the SVG file

      • animated: indicates if the SVG features an animation

      • data: the conten of the SVG file

      Returns

      an image object that can be used as any other image object.

      Throws
      • IOException: if resource lookup fail SVG is unsupported
      Throws:
      IOException
    • createIndexed

      public 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

      Parameters
      • width: image width

      • height: image height

      • palette: the color palette to use with the byte data

      • data: byte data containing palette offsets to map to ARGB colors

      Deprecated

      try to avoid using indexed images explicitly

    • createImage

      public static Image createImage(String path) throws IOException

      Creates an image from a path.

      Parameters
      • path: @param path If path begins with file: then the image will be loaded from FileSystemStorage. Otherwise it will load from the jar resources.
      Returns

      newly created image object

      Throws
      • java.io.IOException
      Throws:
      IOException
    • createImage

      public static Image createImage(Object nativeImage)

      creates an image from the given native image (e.g. MIDP image object)

      Parameters
      • nativeImage
      Returns

      newly created Codename One image object

      Deprecated
    • createImage

      public static Image createImage(InputStream stream) throws IOException

      creates an image from an InputStream

      Parameters
      • stream: a given InputStream
      Returns

      the newly created image

      Throws
      • java.io.IOException
      Throws:
      IOException
    • createImage

      public static Image createImage(int[] rgb, int width, int height)

      creates an image from an RGB image

      Parameters
      • rgb: the RGB image array data

      • width: the image width

      • height: the image height

      Returns

      an image from an RGB image

    • createImage

      public static Image createImage(int width, int height)

      Creates a white opaque mutable image that may be manipulated using #getGraphics().

      The sample below shows this method being used to create a screenshot for sharing the image:

      Form hi = new Form("ShareButton");
      ShareButton sb = new ShareButton();
      sb.setText("Share Screenshot");
      hi.add(sb);
      
      Image screenshot = Image.createImage(hi.getWidth(), hi.getHeight());
      hi.revalidate();
      hi.setVisible(true);
      hi.paintComponent(screenshot.getGraphics(), true);
      
      String imageFile = FileSystemStorage.getInstance().getAppHomePath() + "screenshot.png";
      try(OutputStream os = FileSystemStorage.getInstance().openOutputStream(imageFile)) {
          ImageIO.getImageIO().save(screenshot, os, ImageIO.FORMAT_PNG, 1);
      } catch(IOException err) {
          Log.e(err);
      }
      sb.setImageToShare(imageFile, "image/png");
      

      The sample below demonstrates the drawing of a mask image to create a round image effect

      Toolbar.setGlobalToolbar(true);
      Form hi = new Form("Rounder", new BorderLayout());
      Label picture = new Label("", "Container");
      hi.add(BorderLayout.CENTER, picture);
      hi.getUnselectedStyle().setBgColor(0xff0000);
      hi.getUnselectedStyle().setBgTransparency(255);
      Style s = UIManager.getInstance().getComponentStyle("TitleCommand");
      Image camera = FontImage.createMaterial(FontImage.MATERIAL_CAMERA, s);
      hi.getToolbar().addCommandToRightBar("", camera, (ev) -> {
          try {
              int width = Display.getInstance().getDisplayWidth();
              Image capturedImage = Image.createImage(Capture.capturePhoto(width, -1));
              Image roundMask = Image.createImage(width, capturedImage.getHeight(), 0xff000000);
              Graphics gr = roundMask.getGraphics();
              gr.setColor(0xffffff);
              gr.fillArc(0, 0, width, width, 0, 360);
              Object mask = roundMask.createMask();
              capturedImage = capturedImage.applyMask(mask);
              picture.setIcon(capturedImage);
              hi.revalidate();
          } catch(IOException err) {
              Log.e(err);
          }
      });
      
      Parameters
      • width: the image width

      • height: the image height

      Returns

      an image in a given width and height dimension

    • isAlphaMutableImageSupported

      public static boolean isAlphaMutableImageSupported()

      Returns true if mutable images support alpha transparency

      Returns

      true if mutable images support alpha in their fillColor argument

    • createImage

      public static Image createImage(int width, int height, int fillColor)

      Creates a mutable image that may be manipulated using #getGraphics().

      The sample below shows this method being used to create a screenshot for sharing the image:

      Form hi = new Form("ShareButton");
      ShareButton sb = new ShareButton();
      sb.setText("Share Screenshot");
      hi.add(sb);
      
      Image screenshot = Image.createImage(hi.getWidth(), hi.getHeight());
      hi.revalidate();
      hi.setVisible(true);
      hi.paintComponent(screenshot.getGraphics(), true);
      
      String imageFile = FileSystemStorage.getInstance().getAppHomePath() + "screenshot.png";
      try(OutputStream os = FileSystemStorage.getInstance().openOutputStream(imageFile)) {
          ImageIO.getImageIO().save(screenshot, os, ImageIO.FORMAT_PNG, 1);
      } catch(IOException err) {
          Log.e(err);
      }
      sb.setImageToShare(imageFile, "image/png");
      
      Parameters
      • width: the image width

      • height: the image height

      • fillColor: the color with which the image should be initially filled

      Returns

      an image in a given width and height dimension

    • createImage

      public static Image createImage(byte[] bytes, int offset, int len)

      creates an image from a given byte array data

      Parameters
      • bytes: the array of image data in a supported image format

      • offset: the offset of the start of the data in the array

      • len: the length of the data in the array

      Returns

      the newly created image

    • exifRotation

      public static Image exifRotation(String capturedImage) throws IOException

      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.

      If there is no rotation or flipping, the image is only copied or scaled if necessary; if the capturedImage has a format different from jpeg and png, it is copied as it is. Note that this method doesn't rely on the file extension, but on the mime type of the capturedImage, since some devices don't give appropriate extension to images returned from the gallery.

      You can test all the possible orientation values downloading the images from the repository EXIF Orientation-flag example images

      Code example:

      Form hi = new Form("Hi World", BoxLayout.y());
      Button cameraBtn = new Button("Open Camera");
      Button galleryBtn = new Button("Open Gallery");
      Label imageLbl = new Label();
      hi.addAll(cameraBtn, galleryBtn, FlowLayout.encloseCenter(imageLbl));
      hi.show();
      
      SuccessCallback callback = (String capturedPhoto) -> {
          String rotatedPhoto = FileSystemStorage.getInstance().getAppHomePath() + "rotatedPhoto.jpg";
          if (capturedPhoto != null) {
              try {
                  // note: we set a maxSize to perform a faster rotation
                  int maxSize = CN.convertToPixels(50);
                  Image img = Image.exifRotation(capturedPhoto, rotatedPhoto, maxSize);
                  imageLbl.setIcon(img);
                  hi.revalidate();
              } catch (IOException ex) {
                  Log.e(ex);
              }
          };
      };
      cameraBtn.addActionListener(a -> Capture.capturePhoto(l -> {
          if (l != null && l.getSource() != null) {
              callback.onSucess((String) l.getSource());
          }
      }));
      galleryBtn.addActionListener(a -> CN.openGallery(l -> {
          if (l != null && l.getSource() != null) {
              callback.onSucess((String) l.getSource());
          }
      }, CN.GALLERY_IMAGE));
      
      Parameters
      • capturedImage: @param capturedImage is the FileSystemStorage path of a captured photo, usually inside a temporary directory
      Returns

      the rotated and/or flipped image

      Throws:
      IOException
    • exifRotation

      public static Image exifRotation(String capturedImage, String rotatedImage) throws IOException

      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.

      If there is no rotation or flipping, the image is only copied or scaled if necessary; if the capturedImage has a format different from jpeg and png, it is copied as it is. Note that this method doesn't rely on the file extension, but on the mime type of the capturedImage, since some devices don't give appropriate extension to images returned from the gallery.

      You can test all the possible orientation values downloading the images from the repository EXIF Orientation-flag example images

      Code example:

      Form hi = new Form("Hi World", BoxLayout.y());
      Button cameraBtn = new Button("Open Camera");
      Button galleryBtn = new Button("Open Gallery");
      Label imageLbl = new Label();
      hi.addAll(cameraBtn, galleryBtn, FlowLayout.encloseCenter(imageLbl));
      hi.show();
      
      SuccessCallback callback = (String capturedPhoto) -> {
          String rotatedPhoto = FileSystemStorage.getInstance().getAppHomePath() + "rotatedPhoto.jpg";
          if (capturedPhoto != null) {
              try {
                  // note: we set a maxSize to perform a faster rotation
                  int maxSize = CN.convertToPixels(50);
                  Image img = Image.exifRotation(capturedPhoto, rotatedPhoto, maxSize);
                  imageLbl.setIcon(img);
                  hi.revalidate();
              } catch (IOException ex) {
                  Log.e(ex);
              }
          };
      };
      cameraBtn.addActionListener(a -> Capture.capturePhoto(l -> {
          if (l != null && l.getSource() != null) {
              callback.onSucess((String) l.getSource());
          }
      }));
      galleryBtn.addActionListener(a -> CN.openGallery(l -> {
          if (l != null && l.getSource() != null) {
              callback.onSucess((String) l.getSource());
          }
      }, CN.GALLERY_IMAGE));
      
      Parameters
      • capturedImage: @param capturedImage is the FileSystemStorage path of a captured photo, usually inside a temporary directory

      • rotatedImage: @param rotatedImage is the FileSystemStorage path in which the rotated photo is stored, normally this should be inside the FileSystemStorage.getAppHomePath(); it can be null if you don't want to save the rotated image to the FileSystemStorage.

      Returns

      the rotated and/or flipped image

      Throws:
      IOException
    • exifRotation

      public static Image exifRotation(String capturedImage, String rotatedImage, int maxSize) throws IOException

      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.

      However, rotating and/or flipping an hi-res image is very inefficient, that's why you should consider to pass a maxSize value as small as possible: it makes this method working faster.

      If there is no rotation or flipping, the image is only copied or scaled if necessary; if the capturedImage has a format different from jpeg and png, it is copied as it is. Note that this method doesn't rely on the file extension, but on the mime type of the capturedImage, since some devices don't give appropriate extension to images returned from the gallery.

      You can test all the possible orientation values downloading the images from the repository EXIF Orientation-flag example images

      Code example:

      Form hi = new Form("Hi World", BoxLayout.y());
      Button cameraBtn = new Button("Open Camera");
      Button galleryBtn = new Button("Open Gallery");
      Label imageLbl = new Label();
      hi.addAll(cameraBtn, galleryBtn, FlowLayout.encloseCenter(imageLbl));
      hi.show();
      
      SuccessCallback callback = (String capturedPhoto) -> {
          String rotatedPhoto = FileSystemStorage.getInstance().getAppHomePath() + "rotatedPhoto.jpg";
          if (capturedPhoto != null) {
              try {
                  // note: we set a maxSize to perform a faster rotation
                  int maxSize = CN.convertToPixels(50);
                  Image img = Image.exifRotation(capturedPhoto, rotatedPhoto, maxSize);
                  imageLbl.setIcon(img);
                  hi.revalidate();
              } catch (IOException ex) {
                  Log.e(ex);
              }
          };
      };
      cameraBtn.addActionListener(a -> Capture.capturePhoto(l -> {
          if (l != null && l.getSource() != null) {
              callback.onSucess((String) l.getSource());
          }
      }));
      galleryBtn.addActionListener(a -> CN.openGallery(l -> {
          if (l != null && l.getSource() != null) {
              callback.onSucess((String) l.getSource());
          }
      }, CN.GALLERY_IMAGE));
      
      Parameters
      • capturedImage: @param capturedImage is the FileSystemStorage path of a captured photo, usually inside a temporary directory

      • rotatedImage: @param rotatedImage is the FileSystemStorage path in which the rotated photo is stored, normally this should be inside the FileSystemStorage.getAppHomePath(); it can be null if you don't want to save the rotated image to the FileSystemStorage.

      • maxSize: @param maxSize is the maximum value of the width and height of the rotated images, that is scaled if necessary, keeping the ratio.

      Returns

      the com.codename1.ui.Image

      Throws
      • java.io.IOException
      Throws:
      IOException
    • getExifOrientationTag

      public static int getExifOrientationTag(String path) throws IOException

      Gets the EXIF orientation tag of an image if it's available.

      The Exif Orientation Tag is a number from 0 to 8, for the explanation of each value see the Exif Orientation Tag page

      You can test all the possible orientation values downloading the images from the repository EXIF Orientation-flag example images

      Parameters
      • path: FileSystemStorage path
      Returns
      Returns:

      a value from 0 to 8; 0 is default in case of error or unavailable EXIF data.

      Throws
      • java.io.IOException
      Throws:
      IOException
    • getExifOrientationTag

      public static int getExifOrientationTag(InputStream is)

      Gets the EXIF orientation tag of an image, if it's available.

      The Exif Orientation Tag is a number from 0 to 8, for the explanation of each value see the Exif Orientation Tag page

      You can test all the possible orientation values downloading the images from the repository EXIF Orientation-flag example images

      Parameters
      • is
      Returns
      Returns:
      a value from 0 to 8; 0 is default in case of error or unavailable EXIF data.
    • isJPEG

      public static boolean isJPEG(InputStream inputStream) throws IOException

      Very fast method to detect if the given inputStream is a JPEG image (according to its guessed mime type)

      Parameters
      • inputStream
      Returns

      true if jpeg, false otherwise

      Throws:
      IOException
    • isPNG

      public static boolean isPNG(InputStream inputStream) throws IOException

      Very fast method to detect if the given inputStream is a PNG image (according to its guessed mime type)

      Parameters
      • inputStream
      Returns

      true if PNG, false otherwise

      Throws:
      IOException
    • 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.
    • 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.
    • isLocked

      public boolean isLocked()

      Returns true if the image is locked

      Returns

      false by default

    • unlock

      public void unlock()
      This callback indicates that a component pointing at this image is now deinitilized This method may be invoked multiple times.
    • getSVGDocument

      public Object getSVGDocument()

      Returns a platform specific DOM object that can be manipulated by the user to change the SVG Image

      Returns
      Returns:
      Platform dependent object, when JSR 226 is supported an SVGSVGElement might be returned.
    • isSVG

      public boolean isSVG()

      Indicates if this image represents an SVG file or a bitmap file

      Returns

      true if this is an SVG file

    • createMask

      public Object createMask()

      Creates a mask from the given image, a mask can be used to apply an arbitrary alpha channel to any image. A mask is derived from the blue channel (LSB) of the given image, other channels are ignored.

      The generated mask can be used with the apply mask method.

      The sample below demonstrates the masking of an image based on a circle drawn on a mutable image:

      Toolbar.setGlobalToolbar(true);
      Form hi = new Form("Rounder", new BorderLayout());
      Label picture = new Label("", "Container");
      hi.add(BorderLayout.CENTER, picture);
      hi.getUnselectedStyle().setBgColor(0xff0000);
      hi.getUnselectedStyle().setBgTransparency(255);
      Style s = UIManager.getInstance().getComponentStyle("TitleCommand");
      Image camera = FontImage.createMaterial(FontImage.MATERIAL_CAMERA, s);
      hi.getToolbar().addCommandToRightBar("", camera, (ev) -> {
          try {
              int width = Display.getInstance().getDisplayWidth();
              Image capturedImage = Image.createImage(Capture.capturePhoto(width, -1));
              Image roundMask = Image.createImage(width, capturedImage.getHeight(), 0xff000000);
              Graphics gr = roundMask.getGraphics();
              gr.setColor(0xffffff);
              gr.fillArc(0, 0, width, width, 0, 360);
              Object mask = roundMask.createMask();
              capturedImage = capturedImage.applyMask(mask);
              picture.setIcon(capturedImage);
              hi.revalidate();
          } catch(IOException err) {
              Log.e(err);
          }
      });
      
      Returns

      mask object that can be used with applyMask

    • applyMask

      public Image 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.

      The sample below demonstrates the masking of an image based on a circle drawn on a mutable image:

      Toolbar.setGlobalToolbar(true);
      Form hi = new Form("Rounder", new BorderLayout());
      Label picture = new Label("", "Container");
      hi.add(BorderLayout.CENTER, picture);
      hi.getUnselectedStyle().setBgColor(0xff0000);
      hi.getUnselectedStyle().setBgTransparency(255);
      Style s = UIManager.getInstance().getComponentStyle("TitleCommand");
      Image camera = FontImage.createMaterial(FontImage.MATERIAL_CAMERA, s);
      hi.getToolbar().addCommandToRightBar("", camera, (ev) -> {
          try {
              int width = Display.getInstance().getDisplayWidth();
              Image capturedImage = Image.createImage(Capture.capturePhoto(width, -1));
              Image roundMask = Image.createImage(width, capturedImage.getHeight(), 0xff000000);
              Graphics gr = roundMask.getGraphics();
              gr.setColor(0xffffff);
              gr.fillArc(0, 0, width, width, 0, 360);
              Object mask = roundMask.createMask();
              capturedImage = capturedImage.applyMask(mask);
              picture.setIcon(capturedImage);
              hi.revalidate();
          } catch(IOException err) {
              Log.e(err);
          }
      });
      
      Parameters
      • mask: mask object created by the createMask() method.

      • x: starting x where to apply the mask

      • y: starting y where to apply the mask

      Returns

      image masked based on the given object

    • applyMask

      public Image applyMask(Object 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.

      Parameters
      • mask: mask object created by the createMask() method.
      Returns

      image masked based on the given object

      Throws
      • IllegalArgumentException: if the image size doesn't match the mask size
    • applyMaskAutoScale

      public Image applyMaskAutoScale(Object 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. If the image is of a different size it will be scaled to mask size.

      Parameters
      • mask: mask object created by the createMask() method.
      Returns

      image masked based on the given object

    • 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

    • mirror

      public Image mirror()

      Creates a mirror image for the given image which is useful for some RTL scenarios. Notice that this method isn't the most efficient way to perform this task and is designed for portability over efficiency.

      Returns

      a mirrored 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

    • 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
      Returns:
      Translucent/Opaque image based on the alpha value and the pixels of this image
    • modifyAlphaWithTranslucency

      public Image modifyAlphaWithTranslucency(byte alpha)

      Creates a new image instance with the alpha channel of opaque pixels within the image using the new alpha value. Transparent (alpha == 0) pixels remain transparent. Semi translucent pixels will be multiplied by the ratio difference and their translucency reduced appropriately.

      Parameters
      • alpha: New value for the entire alpha channel
      Returns
      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
      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

    • getWidth

      public int getWidth()

      Returns the width of the image

      Returns

      the width of the image

    • getHeight

      public int getHeight()

      Returns the height of the image

      Returns

      the height of the 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

    • 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

    • 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

    • getRGB

      public int[] getRGB()

      Returns the content of this image as a newly created ARGB array.

      Returns

      new array instance containing the ARGB data within this image

    • getRGB

      public void getRGB(int[] rgbData)

      Returns the content of this image in the supplied ARGB array.

      Parameters
      • rgbData
    • getRGBCached

      public int[] getRGBCached()

      Returns the content of this image as a newly created ARGB array or a cached instance if possible. Note that cached instances may be garbage collected.

      Returns

      array instance containing the ARGB data within this 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

    • 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

    • 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

    • scaledLargerRatio

      public Image scaledLargerRatio(int width, int height)

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

      Parameters
      • width: the given new image width

      • height: the given new image height

      Returns

      the newly created 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

    • fill

      public Image fill(int width, int height)

      Resizes/crops the image so that its center fills the given dimensions. This is similar to com.codename1.ui.plaf.Style#BACKGROUND_IMAGE_SCALED_FILL

      Parameters
      • width: the width to fill

      • height: the height to fill

      Returns

      a new image (or the same image if dimensions happen to match) filling the width/height

    • 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

    • 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
    • isAnimation

      public boolean isAnimation()

      Returns true if this is an animated image

      Returns

      true if this image represents an animation

    • animate

      public boolean animate()
    • 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

    • getImageName

      public String getImageName()

      The name of the image is set for some images mostly to ease the debugging of Codename One application

      Returns

      the imageName

    • setImageName

      public void setImageName(String imageName)

      The name of the image is set for some images mostly to ease the debugging of Codename One application

      Parameters
      • imageName: the imageName to set
    • dispose

      public void dispose()

      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. Images on devices usually holds a native memory, some platforms garbage collectors might fail to release the native and to fail with out of memory errors. Use this method to make sure the image will be released from memory, after calling this the image will become unusable.

      Deprecated

      SERIOUSLY, DON'T INVOKE THIS METHOD UNLESS YOU KNOW WHAT YOU ARE DOING IT WILL CAUSE PLATFORM SPECIFC CRASHES OTHERWISE. IF YOU INVOKED THIS METHOD YOU ARE PROBABLY MAKING A MISTAKE

    • rotate90Degrees

      public Image rotate90Degrees(boolean maintainOpacity)

      Rotates this image by 90 degrees while changing the ratio of the picture

      Parameters
      • maintainOpacity: whether the opacity in the image should be maintained
      Returns

      a new image rotated by 90 degrees

    • rotate180Degrees

      public Image rotate180Degrees(boolean maintainOpacity)

      Rotates the image by 180 degrees

      Parameters
      • maintainOpacity: whether the opacity in the image should be maintained
      Returns

      a new image rotated by 180 degrees

    • rotate270Degrees

      public Image rotate270Degrees(boolean maintainOpacity)

      Rotates the image by 270 degrees while changing the ratio of the picture

      Parameters
      • maintainOpacity: whether the opacity in the image should be maintained
      Returns

      a new image rotated by 270 degrees

    • flipHorizontally

      public Image flipHorizontally(boolean maintainOpacity)

      Flips this image on the horizontal axis

      Parameters
      • maintainOpacity: whether the opacity in the image should be maintained
      Returns

      a new image flipped

    • flipVertically

      public Image flipVertically(boolean maintainOpacity)

      Flips this image on the vertical axis

      Parameters
      • maintainOpacity: whether the opacity in the image should be maintained
      Returns

      a new image flipped

    • requiresDrawImage

      public boolean requiresDrawImage()

      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

    • addActionListener

      public void addActionListener(ActionListener l)
      Description copied from interface: ActionSource

      Adds ActionListener to receive action events form this source.

      Parameters
      • l
      Specified by:
      addActionListener in interface ActionSource
    • removeActionListener

      public void removeActionListener(ActionListener l)
      Description copied from interface: ActionSource

      Removes ActionListener so that it will no longer receive events from this source.

      Parameters
      • l
      Specified by:
      removeActionListener in interface ActionSource
    • fireChangedEvent

      public void fireChangedEvent()