//分割图像的方法。
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import java.net.URL;
import java.io.File;
import java.util.Hashtable;
public class ChenWin504 extends JApplet{
Image im;
MediaTracker me;
Image imag[];
public static Hashtable cache;
public void init(){
URL ur=ChenWin504.class.getResource("images/ima");
imag=new Image[10];
System.out.println(ur);
im=getToolkit().getImage("images/ima/jumptojavastrip.png");
me=new MediaTracker(this);
me.addImage(im,0);
try{
me.waitForID(0);
}catch(Exception e){}
DemoImages();
for(int i=0;i<10;i++){
imag[i]=(Image)cache.get("jumptojavastrip-"+i+".png");
if(imag[i]==null) System.out.println("null");
}
}
public void paint(Graphics g){
int x=5;
int y=100;
g.drawImage(im,5,0,null);
for(int i=0;i<10;i++){
g.drawImage(imag[i],x,y,null);
x+=100;
if(x>300){
x=5;y+=100;
}
}
}
public void DemoImages() {
URL url = ChenWin504.class.getResource("images/ima");
File dir = new File(url.getFile());
if (dir != null && dir.isDirectory()) {
String list[] = dir.list();
System.out.println(list.length);
cache = new Hashtable(list.length);
for (int i = 0; i < list.length; i++) {
cache.put(list[i], createImage(list[i], this));
}
}
if (cache.containsKey("jumptojavastrip.png")) {
Image img = (Image) cache.get("jumptojavastrip.png");
for (int i=0, x=0; i < 10; i++, x+=80) {
String s = "jumptojavastrip-" + String.valueOf(i) + ".png";
cache.put(s, getCroppedImage(img, x, 0, 80, 80, this));
}
}
}
public static Image createImage(String fileName, Component cmp) {
URL url = ChenWin504.class.getResource("images/ima/" + fileName);
Image img = cmp.getToolkit().createImage(url);
trackImage(img, cmp);
return img;
}
//分割图像的方法。
public static Image getCroppedImage(Image img,
int x, int y,
int w, int h,
Component cmp) {
ImageProducer imgP = img.getSource();
CropImageFilter cif = new CropImageFilter(x, y, w, h);
ImageProducer ip = new FilteredImageSource(imgP, cif);
Image croppedimage = cmp.getToolkit().createImage(ip);
trackImage(croppedimage, cmp);
return croppedimage;
}
private static void trackImage(Image img, Component cmp) {
MediaTracker tracker = new MediaTracker(cmp);
tracker.addImage(img, 0);
try {
tracker.waitForID(0);
} catch (Exception ex) { ex.printStackTrace(); }
}
}
效果图: