Monday, March 14, 2011

Canvas ScreenShot in JavaMe

Due to the previous posts about image encoding and image's bytes, I found an interesting question about how to get a screenshot of a canvas in JavaMe and it turns out to be very simple. Just remember, once you get the mutable (changeable) Image you should encode it in some format (i.e. PNG, JPEG, etc...).

The following is a regular canvas class which paints a smily:

  
//imports...
public class MyCanvas extends Canvas {
    
    /**
     * Creates a mutable image representing a screenshot of the
     * canvas
     * @return Screenshot as a mutable image
     */
    public Image getScreenShot() {
      Image screenshot = Image.createImage(getWidth(), 
                         getHeight());
      Graphics g = screenshot.getGraphics();
      paint(g);
      return screenshot;
    }

    /**
     * Painting method
     * @param g Graphic object to which the painting is done
     */
    public void paint(Graphics g) {
      //change to black an paint the whole background
      g.setColor(0x000000);
      g.fillRect(0, 0, getWidth(), getHeight());

      //change to yellow
      g.setColor(0xFFFF00);
      //left|top position of the face so it seems centered
      int xCenter = (getWidth() - 80) / 2;
      int yCenter = (getHeight() - 80) / 2;
      //draw the face
      g.fillArc(xCenter, yCenter, 80, 80, 0, 360);
      //change to black color
      g.setColor(0x000000);
      //left eye
      g.fillArc(xCenter + 20, yCenter + 20, 10, 15, 0, 360);
      //right eye
      g.fillArc(xCenter + 50, yCenter + 20, 10, 15, 0, 360);
      //smile
      g.fillArc(xCenter + 15, yCenter + 50, 50, 10, 180, 180);

    }
  }

Notice that the +getScreenShot():Image method is creating a mutable image of the same width and height of the canvas. It also gets the Graphic object from that image so that the paint method can draw the smily on it.

What to do with the screenshot? As I told you before, it's up to you. You can convert it to bytes, save it using RMS or FileConnection API, send it over the network...etc. But whatever you choose to do, remember to encode it using PNG or JPEG encoders, otherwise your end user may not be able to see or manipulate the image.

see ya soon!

References:

A minimal PNG encoder for J2ME. 2009. [online].
Available on Internet: http://www.chrfr.de/software/midp_png.html
[accessed on March 12 2011].

J2ME Screenshot of a Canvas. March 2010. Forum.Nokia [online].
Available on Internet: http://discussion.forum.nokia.com/forum/showthread.php?191207-J2ME-Screenshot-of-a-Canvas
[accessed on March 12 2011].

PNG Encoding in Java ME. March 2010. Forum.Nokia [online].
Available on Internet: http://wiki.forum.nokia.com/index.php/PNG_Encoding_in_Java_ME
[accessed on March 12 2011].