Java图像缩放japplet [英] Java image zooming japplet

查看:100
本文介绍了Java图像缩放japplet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图制作一个允许我打开,放大和缩小图像的小程序。我有一个工作小程序,但我有缩放问题。关于从哪里到这里的任何想法?

Im trying to make an applet that will allow me to open, zoom in and out of an image. Ive got a working applet going, but am having trouble with the zoom. Any ideas on where to head from here?

这是我到目前为止

ImageZoom

ImageZoom

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.awt.image.*;
import java.io.*;



public class ImageZoom extends JApplet implements ActionListener
{
JPanel jpanel, pane2;
JLabel image;
JButton open_file, zoom_in, zoom_out;
Image img;
JFileChooser fc;
Zoom zP;

@Override
public void init() 
{
   setSize(450,450);
   buttonLayout();
   filechooser();
   imgLayout();
   zP = new Zoom();
}   

public void imgLayout()
{
    pane2 = new JPanel();
    pane2.setLayout(new BorderLayout());
    image = new JLabel("");
    pane2.add(image,BorderLayout.CENTER);
}

public void buttonLayout()
{
    jpanel = new JPanel(new FlowLayout());

    open_file = new JButton("Open file");
    open_file.addActionListener(this);
    jpanel.add(open_file);

    zoom_in = new JButton("Zoom In");
    zoom_in.addActionListener(this);
    jpanel.add(zoom_in);

    zoom_out = new JButton("Zoom Out");
   zoom_out.addActionListener(this);
    jpanel.add(zoom_out);

    add( jpanel, BorderLayout.NORTH );
}

public void filechooser()
{
    fc = new JFileChooser();
    fc.setCurrentDirectory(new File(
            System.getProperty("user.home")));
}    



@Override
public void actionPerformed(ActionEvent ae) 
{

    if(ae.getSource() == open_file)
    {
    int result = fc.showOpenDialog(null );
    if(result == JFileChooser.APPROVE_OPTION)
    {
        File file = fc.getSelectedFile();
        String sname = file.getAbsolutePath();
        image = new JLabel("", new ImageIcon(sname), JLabel.CENTER);
        jpanel.add(image, BorderLayout.CENTER);
        jpanel.revalidate();
        jpanel.repaint();
    }
  }    
    else if(ae.getSource() == zoom_in)
    {
        zP.increaseSize();
    }
    else if(ae.getSource() == zoom_out)
    {
        zP.decreaseSize();
    }
}
}

缩放

import java.awt.*;  
import java.awt.event.*;  
import java.applet.*;  


class Zoom extends Panel
{  
MediaTracker tracker;  
Image img;  
Dimension imgSize,iniSize;  

public Zoom()
{  
setSize(400,275);  
img =Toolkit.getDefaultToolkit().getImage("image"); // here u give ur own image name  
tracker=new MediaTracker(this);  
tracker.addImage(img,1);  

try{  
tracker.waitForAll();  
}  
catch(InterruptedException ie){  
System.out.println("Error in loading image");  
}  

  imgSize=iniSize=new Dimension(img.getWidth(this),img.getHeight(this));  

}  

@Override
public Dimension getPreferredSize(){  
return new Dimension(imgSize);  

}  

public void decreaseSize()
{  
    int x=10*imgSize.width/100;  
    int y=10*imgSize.height/100;  

    imgSize=new Dimension(imgSize.width-x,imgSize.height-y);  

    if(getWidth()>iniSize.width)
    {  
    setSize(imgSize);  
    getParent().doLayout();  
    }  
repaint();  
} 

    public void increaseSize()
{  
    int x=10*imgSize.width/100;   
    int y=10*imgSize.height/100;  
    imgSize = new Dimension(imgSize.width+x,imgSize.height+y);   
    if(imgSize.width>iniSize.width)
{  
    setSize(imgSize);  
    getParent().doLayout();  
}
 repaint();
}

}  // class Zoom


推荐答案

您可以继续使用 JLabel 并缩放图像并重置 JLabel s icon 属性,或者您可以创建专用于该作业的自定义组件...

You could continue to use a JLabel and scale the image and reset the JLabels icon property, or you could create a custom component dedicated to the job...

首先,我们需要显示图像...

To start with, we need to display the image...

public class ZoomPane extends JPanel {

    private BufferedImage master;
    private Image scaled;
    private float scale = 1f;

    public ZoomPane() {
        try {
            master = ImageIO.read(new File("..."));
            scaled = master;
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public Dimension getPreferredSize() {
        return scaled != null ? new Dimension(scaled.getWidth(this), scaled.getHeight(this)) : new Dimension(200, 200);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (scaled != null) {
            Graphics2D g2d = (Graphics2D) g.create();
            int x = (getWidth() - scaled.getWidth(this)) / 2;
            int y = (getHeight() - scaled.getHeight(this)) / 2;
            g2d.drawImage(scaled, x, y, this);
            g2d.dispose();
        }
    }

}

现在,您可以使用 MouseWheelListener 来缩放图像...

Now, you could use a MouseWheelListener to scale the image...

addMouseWheelListener(new MouseWheelListener() {
    @Override
    public void mouseWheelMoved(MouseWheelEvent e) {
        if (e.getWheelRotation() < 0) {
            scale -= 0.1;
        } else {
            scale += 0.1;
        }
        scaleBy(scale);
    }
});

因为您可能希望允许用户使用几种不同的方法来缩放图像,很方便的方法....

And because you'll probably want to allow the users a few different methods to scale the image, a nice convenience method....

public void scaleBy(float amount) {
    scale += amount;
    scale = Math.min(Math.max(scale, 0.1f), 200);
    scaled = master.getScaledInstance(
                    Math.round(master.getWidth() * scale),
                    Math.round(master.getHeight() * scale),
                    Image.SCALE_SMOOTH);
    revalidate();
    repaint();
}

现在,允许用户使用< kbd> + 和 - 键,为此,我们需要某种 Action ...

Now, it'd probably be nice to allow the user to use the + and - keys, for this, we'll want some kind of Action...

public class ZoomAction extends AbstractAction {
    private ZoomPane zoomPane;
    private float zoomAmount;

    public ZoomAction(ZoomPane zoomPane, String name, float zoomAmount) {
        this.zoomAmount = zoomAmount;
        this.zoomPane = zoomPane;
        putValue(NAME, name);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        zoomPane.scaleBy(zoomAmount);
        System.out.println("...");
    }

}

这允许我们绑定键盘动作,按钮和菜单,并重复使用相同的基本代码...

This allows us to bind keyboard actions, buttons and menus and re-use the same basic code to do it...

InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ADD, 0), "zoom-in");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_SUBTRACT, 0), "zoom-out");

am.put("zoom-in", new ZoomAction(this, "Zoom in", 0.1f));
am.put("zoom-out", new ZoomAction(this, "Zoom out", -0.1f));

此示例适用于小键盘 + - keys。

This example works with the numpad + and - keys.

所有这些功能都应直接添加到 ZoomPane

All this functionality should be added directly within the ZoomPane

您可以在菜单中重复使用 ZoomAction ...

You can re-use the ZoomAction in your menus...

JMenuBar mb = new JMenuBar();
JMenu pictureMenu = new JMenu("Picture");
pictureMenu.add(new ZoomAction(zoomPane, "Zoom In", 0.1f));
pictureMenu.add(new ZoomAction(zoomPane, "Zoom Out", -0.1f));
mb.add(pictureMenu);

即使在按钮中......

And even in you buttons...

JPanel buttons = new JPanel();
buttons.add(new JButton(new ZoomAction(zoomPane, "Zoom In", 0.1f)));
buttons.add(new JButton(new ZoomAction(zoomPane, "Zoom Out", -0.1f)));
frame.add(buttons, BorderLayout.SOUTH);



警告



缩放比较粗糙准备好了,你应该考虑看看:

Warning

The scaling is pretty rough and ready, you should consider taking a look at:

  • The Perils of Image.getScaledInstance()
  • Java: maintaining aspect ratio of JPanel background image
  • Quality of Image after resize very low -- Java

...了解更多详情

最后,将它们作为一个可运行的示例进行一起攻击...

And finally, hacking it all together, as a runnable example...

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

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

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                ZoomPane zoomPane = new ZoomPane();

                JMenuBar mb = new JMenuBar();
                JMenu pictureMenu = new JMenu("Picture");
                pictureMenu.add(new ZoomAction(zoomPane, "Zoom In", 0.1f));
                pictureMenu.add(new ZoomAction(zoomPane, "Zoom Out", -0.1f));

                mb.add(pictureMenu);

                JFrame frame = new JFrame("Testing");
                frame.setJMenuBar(mb);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(zoomPane);

                JPanel buttons = new JPanel();
                buttons.add(new JButton(new ZoomAction(zoomPane, "Zoom In", 0.1f)));
                buttons.add(new JButton(new ZoomAction(zoomPane, "Zoom Out", -0.1f)));
                frame.add(buttons, BorderLayout.SOUTH);

                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class ZoomPane extends JPanel {

        private BufferedImage master;
        private Image scaled;
        private float scale = 1f;

        public ZoomPane() {
            try {
                master = ImageIO.read(new File("C:\\Users\\shane\\Dropbox\\MegaTokyo\\megatokyo_omnibus_1_3_cover_by_fredrin-d4oupef.jpg"));
                scaled = master;

                addMouseWheelListener(new MouseWheelListener() {
                    @Override
                    public void mouseWheelMoved(MouseWheelEvent e) {
                        if (e.getWheelRotation() < 0) {
                            scale -= 0.1;
                        } else {
                            scale += 0.1;
                        }
                        scaleBy(scale);
                    }
                });

                InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
                ActionMap am = getActionMap();
                im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ADD, 0), "zoom-in");
                im.put(KeyStroke.getKeyStroke(KeyEvent.VK_SUBTRACT, 0), "zoom-out");

                am.put("zoom-in", new ZoomAction(this, "Zoom in", 0.1f));
                am.put("zoom-out", new ZoomAction(this, "Zoom out", -0.1f));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        public void scaleBy(float amount) {
            scale += amount;
            scale = Math.min(Math.max(scale, 0.1f), 200);
            scaled = master.getScaledInstance(
                            Math.round(master.getWidth() * scale),
                            Math.round(master.getHeight() * scale),
                            Image.SCALE_SMOOTH);
            revalidate();
            repaint();
        }

        @Override
        public Dimension getPreferredSize() {
            return scaled != null ? new Dimension(scaled.getWidth(this), scaled.getHeight(this)) : new Dimension(200, 200);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (scaled != null) {
                Graphics2D g2d = (Graphics2D) g.create();
                int x = (getWidth() - scaled.getWidth(this)) / 2;
                int y = (getHeight() - scaled.getHeight(this)) / 2;
                g2d.drawImage(scaled, x, y, this);
                g2d.dispose();
            }
        }

    }

    public class ZoomAction extends AbstractAction {
        private ZoomPane zoomPane;
        private float zoomAmount;

        public ZoomAction(ZoomPane zoomPane, String name, float zoomAmount) {
            this.zoomAmount = zoomAmount;
            this.zoomPane = zoomPane;
            putValue(NAME, name);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            zoomPane.scaleBy(zoomAmount);
            System.out.println("...");
        }

    }

}

这篇关于Java图像缩放japplet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆