⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 example6_11.java

📁 书中的例题
💻 JAVA
字号:
/* 图像处理 */
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*; 
class Example6_11 extends Frame  { 
  Image  img,cropped;
  int    x,w,h;
  int[]  pixels  ;

  public static void main(String[] args) 
	{ new Example6_11();	}

  private class WindowCloser extends WindowAdapter
   {  public void windowClosing(WindowEvent we)
	   {System.exit(0);}	    
   }
  
 Example6_11() {
   setSize(550,400);show();
   takeimg();
   addWindowListener(new WindowCloser());
  }

  //获取图像
 public void takeimg(){
  MediaTracker tracker=new MediaTracker(this);
  img=Toolkit.getDefaultToolkit().getImage("a.jpg");
  tracker.addImage(img,0);
  try{ tracker.waitForID(0); }
  catch(InterruptedException e) { }
  w=img.getWidth(this);
  h=img.getHeight(this);
  pixels=new int[w*h];
   //抓取图像的像素放到数组中,注意要使用try-catch 结构
  try{
	  PixelGrabber pg = new  PixelGrabber(img,0,0,w,h,pixels,0,w);
	  pg.grabPixels();  
     }catch(InterruptedException e) { }
  madeimg();
 }

 public void madeimg(){
   //对RGB值和Alpha值进行重新计算和赋值
  filterRGB();
  //通过MemoryImageSource将数组中的像素产生一个新图像
  ImageProducer imgprd=new MemoryImageSource(w,h,pixels,0,w);
  cropped= createImage(imgprd);
  MediaTracker tracker2=new MediaTracker(this);
  tracker2.addImage(cropped,1);
  try{ tracker2.waitForID(1); }
  catch(InterruptedException e) {    }
}

   //对RGB值进行重新计算和赋值
 public void filterRGB() {
  ColorModel cm=ColorModel.getRGBdefault();
  for (x=0;x<w*h ;x++ )
   {
   int r = 0xff - cm.getRed(pixels[x]) & 0xff;
   int g = 0xff - cm.getGreen(pixels[x]) & 0xff;  
   int b = 0xff - cm.getBlue(pixels[x]) & 0xff;
   pixels[x]=0xff000000 |r << 16 | g << 8 | b ; 
   }
 }

 public void paint(Graphics g){
    //显示原图像
    g.drawImage(img,10,20,this);   

	//延时
    try {Thread.sleep(100); }
    catch(InterruptedException e) { }

    //显示经数组处理后的图像
    try{ g.drawImage(cropped,w+20, 20,this);  } 
    catch(Exception e) {   }
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -