翻转图像 站点:爱心种子小博士 关键字:翻转图像
|
翻转图像 程序运行图:
//翻转图像
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
public class TRaster72 extends JFrame{
DisplayPanel displayPanel;
JToggleButton flipButton;
public TRaster72(){
super("TRaster");
Container container=getContentPane();
displayPanel=new DisplayPanel();
container.add(displayPanel);
Box box=Box.createHorizontalBox();
flipButton=new JToggleButton("Flip the Image");
flipButton.addActionListener(new ButtonListener());
box.add(Box.createHorizontalGlue());
box.add(flipButton);
box.add(Box.createHorizontalGlue());
container.add(box,BorderLayout.SOUTH);
addWindowListener(new WindowEventHandler());
setSize(600,450);
show();
}
class WindowEventHandler extends WindowAdapter{
public void windowClosing(WindowEvent e){
System.exit(0);
}
}
public static void main(String args[]){
new TRaster72();
}
class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e){
if(!displayPanel.flipped){
displayPanel.flipBufferedImage();
displayPanel.bi=displayPanel.bi2;
displayPanel.flipped=true;
}
else {
displayPanel.bi=displayPanel.bi1;
displayPanel.flipped=false;
}
displayPanel.repaint();
}
}
}
class DisplayPanel extends JPanel{
BufferedImage bi,bi1,bi2;
boolean flipped=false;
DisplayPanel(){
setBackground(Color.white);
setSize(450,400);
Image image=getToolkit().getImage("image/5.jpg");
MediaTracker mt=new MediaTracker(this);
mt.addImage(image,1);
try{
mt.waitForAll();
}catch(Exception e){
System.out.println("Exception while loading image.");
}
if(image.getWidth(this)==-1){
System.out.println("********");
System.exit(0);
}
bi1=new BufferedImage(image.getWidth(this),
image.getHeight(this),
BufferedImage.TYPE_INT_ARGB);
Graphics2D big=bi1.createGraphics();
big.drawImage(image,0,0,this);
bi=bi1;
}
public void flipBufferedImage(){
bi2=new BufferedImage(bi1.getWidth(),bi1.getHeight(),bi1.getType());
DataBuffer db1=bi1.getRaster().getDataBuffer();
DataBuffer db2=bi2.getRaster().getDataBuffer();
for(int i=db1.getSize()-1,j=0;i>=0;--i,j++){
db2.setElem(j,db1.getElem(i));
}
}
public void update(Graphics g){
g.clearRect(0,0,getWidth(),getHeight());
paintComponent(g);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d=(Graphics2D)g;
g2d.drawImage(bi,0,0,this);
}
}
|
|
|
|