Wednesday, December 12, 2012

Menampilkan gambar dalam bentuk thumbnail pada JAVA (J2ME)


import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.IOException;

public class Thumbnail extends MIDlet
  implements CommandListener {
   
  private Display display;
  private Form form;
   
  private final Command cmdKeluar =
    new Command("Keluar", Command.EXIT, 1);
   
  public Thumbnail() {
    display = Display.getDisplay(this);
  }
   
  public void startApp() {       
       
   form = new Form("Tampilan Thumbnail");
       
   Image image1 = null, image2 = null,
   image3 = null, image4 = null;

   try {
     image1 = Image.createImage("/icons/image1.jpg");
     image2 = Image.createImage("/icons/image2.jpg");
     image3 = Image.createImage("/icons/image3.jpg");
     image4 = Image.createImage("/icons/image4.jpg");
   } catch (IOException ioe) {
     ioe.printStackTrace();
   }
               
   form.append(createPreview(image1));
   form.append(createPreview(image2));
   form.append(createPreview(image3));
   form.append(createPreview(image4));
               
   form.addCommand(cmdKeluar);
   form.setCommandListener(this);       

   display.setCurrent(form);
  }
   
  public void pauseApp() {
  }
   
  public void destroyApp(boolean unconditional) {
  }
   
  public void commandAction(Command c, Displayable s) {
    if (c == cmdKeluar) {
      destroyApp(false);
      notifyDestroyed();
    }
  }
      
  public static Image createPreview (Image image) {
    int sw = image.getWidth();
    int sh = image.getHeight();

    int pw = 82;
    int ph = pw * sh / sw;

    Image temp = Image.createImage(pw, ph);
    Graphics g = temp.getGraphics();

    for (int y = 0; y < ph; y++) {
      for (int x = 0; x < pw; x++) {
         g.setClip(x, y, 1, 1);
         int dx = x * sw / pw;
         int dy = y * sh / ph;
         g.drawImage(image, x - dx, y - dy,
         Graphics.LEFT | Graphics.TOP);
      }
    }

    Image preview = Image.createImage(temp);
    return preview;
  }       
}

No comments:

Post a Comment