第6周作业-图像缩放显示

来源:互联网 发布:怎么看淘宝的图片大小 编辑:程序博客网 时间:2024/05/16 04:17

1、书本例题P201源程序ShowingImg.java,缩放显示图像

import javax.swing.*;import java.awt.*;public class ShowImg extends JApplet{Image img1;public void init(){img1 = getImage(getCodeBase(),"a.gif");    //图片存放在bin目录下}public void paint(Graphics g){int w = img1.getWidth(this);                //获取原图宽度int h = img1.getHeight(this);               //获取原图高度g.drawImage(img1,5,10,this);                //原图显示g.drawImage(img1,150,40,w/2,h/2,this);      //宽度、高度缩小一半显示g.drawImage(img1,5,100,w*2,h*2,this);       //宽度、高度放大一半显示}}


 

2、把Applet改写为Application,含有main主方法的应用程序,类似于P199 例9-12

import javax.swing.*;import java.awt.*;public class ImageShow {       public static void main(String args[]){       ImageFrame frame = new ImageFrame();       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       frame.setVisible(true);       }}class ImageFrame extends JFrame{public ImageFrame(){setTitle("ImageShow");setSize(WIDTH,HEIGHT);ImagePanel panel = new ImagePanel();Container contentPane = getContentPane();contentPane.add(panel);}public static final int WIDTH = 300;public static final int HEIGHT = 200;}class ImagePanel extends JPanel{public ImagePanel(){img = Toolkit.getDefaultToolkit().getImage("a.gif");MediaTracker tracker = new MediaTracker(this);tracker.addImage(img,1);try{tracker.waitForID(1);}catch(InterruptedException exception){}}public void paintComponent(Graphics g){super.paintComponent(g);int imageWidth = img.getWidth(this);                        //获取原图宽度int imageHeight = img.getHeight(this);                      //获取原图高度int FrameWidth = getWidth();                                  int FrameHeight = getHeight();g.drawImage(img,5,10,this);                                 //原图显示g.drawImage(img,150,40,imageWidth/2,imageHeight/2,this);    //宽度、高度缩小一半显示g.drawImage(img,5,100,imageWidth*2,imageHeight*2,this);     //宽度、高度放大一半显示}private Image img;}


0 0