改正了JAVA案例开发集锦中案例五的错误 import java.applet.*; import java.awt.*; import java.awt.image.*; public class tt4 extends Applet { /** * */ private static final long serialVersionUID = 1L; Image art,Buf; int onced = 0; boolean is_color = true; Graphics Bufg; //使用双缓冲区技术抑制闪烁 Dimension xy = null; //存储一个对象的尺寸 public void init(){ art = getImage(getDocumentBase(),"test.jpg"); resize(640, 480); //装入图片 } public void paint(Graphics g){ if(onced == 0){ //如果是第一次装入图片,则直接显示 g.drawImage(art,0,0,this); } if((onced == 1) || (onced == 2)){ //如果正在进行灰度变换,则提示等待 g.setColor(new Color(255,200,0)); g.drawString("正在转换~", 1, 30); } if(onced == 3){ //如果灰度变换完毕,则显示结果 if(is_color) g.drawImage(Buf,0,0,this); else g.drawImage(art, 0, 0, this); is_color = !is_color; //在彩色与黑色直接变化 } } public boolean mouseDown(Event evt, int x, int y){ if(onced == 0){ onced = 1; } repaint(); //用鼠标触发事件 return true; } public boolean mouseUp(Event evt, int x, int y){ if(onced == 1){ onced = 2; int wd = art.getWidth(this); //取得图片宽 int ht = art.getHeight(this); //取得图片高 GetPixels(art,0,0,wd,ht); //调用灰度变换方法 } return true; } public void GetPixels(Image img, int x, int y, int w, int h){ int[] pixels = new int[w*h]; //定义一块内存空间 int gray; PixelGrabber pg = new PixelGrabber(img, x, y, w, h, pixels, 0, w); try{ pg.grabPixels(); //读取像素值 }catch (InterruptedException e){ System.err.println("interrupted waiting for pixels!"); //return ; } for(int j = 0; j < h; j++){ //长宽不要弄错了******* for(int i = 0; i < w; i++){ gray = (int)(((pixels[w*j+i]>>16)&0xff)*0.3); gray +=(int)(((pixels[w*j+i]>>8)&0xff)*0.59); gray += (int)(((pixels[w*j+i])&0xff)*0.11); //由红,绿,蓝值得到灰度值 pixels[w*j+i] = (255<<24)|(gray<<16)|(gray<<8)|gray; } } Image pic = createImage(new MemoryImageSource(w, h, pixels, 0, w)); Bufg.drawImage(pic, 0, 0, this); //显示黑白图片 onced = 3; repaint(); } @SuppressWarnings("deprecation") public void update(Graphics g){ if(xy == null){ xy = this.size(); Buf = createImage(xy.width, xy.height); Bufg = Buf.getGraphics(); } paint(g); //修改update的方法 } } HTML代码 <html> <head> <title>对彩色图片进行灰度变换</title> <body> <p align="center"> <applet code=tt4.class name=test.jpg width=440 height=440 > </applet> </body> </html>