如何用java swing写出一个自拍头像上传头像的界面

这篇博客展示了如何使用Java Swing构建一个自拍头像上传界面,包括选择本地图片、显示预览和捕获自拍等功能,涉及文件过滤、图像处理等技术。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by asus on 2017/3/31.
 */
public class qqHeadFrame extends JFrame implements ActionListener {
    private JPanel cardPanel;
    private JPanel buttonPanel;
    private JPanel firstPanel, secondPanel, thirdPanel;
    private CardLayout cardLayout;
    private JButton firstButton, secondButton, thirdButton, localPicButton, selPicButton;
    private JLabel photoLabel;
    private JFileChooser jc;

    public qqHeadFrame() {
        init();
        setTitle("更换头像");
        setSize(625, 470);
        setLocationRelativeTo(null);
        setVisible(true);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        initFileChooser();
    }

    public void init() {
        add(getButtonPanel(), BorderLayout.NORTH);
        add(getCardPanel(), BorderLayout.CENTER);
    }

    private void initFileChooser() {
        jc = new JFileChooser();
        jc.addChoosableFileFilter(new FileFilter() {
            @Override
            public boolean accept(File f) {
                if (f.isDirectory())
                    return true;
                if (f.getName().endsWith(".png")
                        || f.getName().endsWith(".jpg")
                        || f.getName().endsWith(".gif"))
                    return true;
                return false;
            }

            @Override
            public String getDescription() {
                return "*.png|*.jpg|*.gif";
            }
        });
    }

    public JPanel getButtonPanel() {
        buttonPanel = new JPanel();
        firstButton = new JButton("自定义头像");
        secondButton = new JButton("经典头像");
        thirdButton = new JButton("动态头像");
        firstButton.addActionListener(this);
        secondButton.addActionListener(this);
        thirdButton.addActionListener(this);
        buttonPanel.add(firstButton);
        buttonPanel.add(secondButton);
        buttonPanel.add(thirdButton);
        return buttonPanel;
    }

    public JPanel getCardPanel() {
        cardLayout = new CardLayout();
        cardPanel = new JPanel(cardLayout);
        cardPanel.add(getFirstPanel(), "first");
        cardPanel.add(getSecondPanel(), "second");
        cardPanel.add(getThirdPanel(), "third");
        return cardPanel;
    }

    public JPanel getFirstPanel() {
        firstPanel = new JPanel();
        firstPanel.setBackground(new Color(164, 217, 248));
        firstPanel.setLayout(null);
        localPicButton = new JButton("本地照片");
        selPicButton = new JButton("自拍头像");
        localPicButton.setBounds(8, 8, 120, 24);
        selPicButton.setBounds(136, 8, 120, 24);
        localPicButton.addActionListener(this);
        selPicButton.addActionListener(this);
        firstPanel.add(localPicButton);
        firstPanel.add(selPicButton);
        photoLabel = new JLabel();
        photoLabel.setBounds(180, 70, 250, 250);
        photoLabel.setOpaque(true);
        photoLabel.setBackground(new Color(255, 193, 134));
        firstPanel.add(photoLabel);
        return firstPanel;
    }

    public JPanel getSecondPanel() {
        secondPanel = new JPanel();
        return secondPanel;
    }

    public JPanel getThirdPanel() {
        thirdPanel = new JPanel();
        return thirdPanel;
    }

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

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == localPicButton) {
            jc.setFileSelectionMode(JFileChooser.FILES_ONLY);
            jc.setDialogTitle("请选择文件");
            int result = jc.showOpenDialog(null);
            if (result == JFileChooser.APPROVE_OPTION) {
                File file = jc.getSelectedFile(); //获得用户选择的文件
                InputStream inputStream = null;
                byte[] b = new byte[(int) file.length()];
                try {
                    inputStream = new FileInputStream(file);
                    inputStream.read(b);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                Icon icon = new ImageIcon(b);
                photoLabel.setIcon(icon);
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            } else {
                System.out.println("没有选择任何文件");
            }
        }
        if (e.getSource() == secondButton) {
            JOptionPane.showMessageDialog(null, "等待系统完善");
        }
        if (e.getSource() == thirdButton) {
            JOptionPane.showMessageDialog(null, "等待系统完善");
        }
        if (e.getSource() == selPicButton) {
            picCaptureDialog picCapture = new picCaptureDialog(this);
            String filePath = picCapture.getFilePath();
            if (null == filePath) {
                return;
            }
            try {
                BufferedImage bImage = ImageIO.read(new File(filePath));
                ImageIcon image = new ImageIcon(Toolkit.getDefaultToolkit().createImage(bImage.getSource()));
                image.setImage(image.getImage().getScaledInstance(photoLabel.getWidth(), photoLabel.getHeight(),
                        Image.SCALE_DEFAULT));
                photoLabel.setIcon(image);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

}
    public class BitConverter {
    public static void fromLong(long value, byte[] buffer, int offset, boolean isBigEndian) {
        buffer[offset + (isBigEndian ? 0 : 7)] = (byte) (value >> 56 & 0xFF);
        buffer[offset + (isBigEndian ? 1 : 6)] = (byte) (value >> 48 & 0xFF);
        buffer[offset + (isBigEndian ? 2 : 5)] = (byte) (value >> 40 & 0xFF);
        buffer[offset + (isBigEndian ? 3 : 4)] = (byte) (value >> 32 & 0xFF);
        buffer[offset + (isBigEndian ? 4 : 3)] = (byte) (value >> 24 & 0xFF);
        buffer[offset + (isBigEndian ? 5 : 2)] = (byte) (value >> 16 & 0xFF);
        buffer[offset + (isBigEndian ? 6 : 1)] = (byte) (value >> 8 & 0xFF);
        buffer[offset + (isBigEndian ? 7 : 0)] = (byte) (value & 0xFF);
    }

    public static void fromInt(int value, byte[] buffer, int offset, boolean isBigEndian) {
        buffer[offset + (isBigEndian ? 0 : 3)] = (byte) (value >> 24 & 0xFF);
        buffer[offset + (isBigEndian ? 1 : 2)] = (byte) (value >> 16 & 0xFF);
        buffer[offset + (isBigEndian ? 2 : 1)] = (byte) (value >> 8 & 0xFF);
        buffer[offset + (isBigEndian ? 3 : 0)] = (byte) (value & 0xFF);
    }

    public static void fromShort(short value, byte[] buffer, int offset, boolean isBigEndian) {
        buffer[offset + (isBigEndian ? 0 : 1)] = (byte) (value >> 8 & 0xFF);
        buffer[offset + (isBigEndian ? 1 : 0)] = (byte) (value & 0xFF);
    }

    public static long toLong(byte[] buffer, int offset, boolean isBigEndian) {
        return (long) (buffer[offset + (isBigEndian ? 0 : 7)]) << 56
                | (long) (buffer[offset + (isBigEndian ? 1 : 6)]) << 48
                | (long) (buffer[offset + (isBigEndian ? 2 : 5)]) << 40
                | (long) (buffer[offset + (isBigEndian ? 3 : 4)]) << 32
                | (long) (buffer[offset + (isBigEndian ? 4 : 3)]) << 24
                | (long) (buffer[offset + (isBigEndian ? 5 : 2)]) << 16
                | (long) (buffer[offset + (isBigEndian ? 6 : 1)]) << 8
                | (long) (buffer[offset + (isBigEndian ? 7 : 0)]);
    }

    public static int toInt(byte[] buffer, int offset, boolean isBigEndian) {
        return buffer[offset + (isBigEndian ? 0 : 3)] << 24
                | buffer[offset + (isBigEndian ? 1 : 2)] << 16
                | buffer[offset + (isBigEndian ? 2 : 1)] << 8
                | buffer[offset + (isBigEndian ? 3 : 0)];
    }

    public static short toShort(byte[] buffer, int offset, boolean isBigEndian) {
        return (short) (buffer[offset + (isBigEndian ? 0 : 1)] << 8
                | buffer[offset + (isBigEndian ? 1 : 0)]);
    }
}
public class ClockThread extends Thread {
    private ThreadProc threadProc;
    private int interval;
    private boolean isContinue;
    private Object lock;//线程同步

    public ClockThread(ThreadProc threadProc) {
        this.threadProc = threadProc;
        this.lock = new Object();
    }

    public ClockThread(ThreadProc threadProc, int interval) {
        this.threadProc = threadProc;
        this.interval = interval;
        this.lock = new Object();
    }

    public int getInterval() {
        synchronized (this.lock) {
            return interval;
        }
    }

    public void setInterval(int interval) {
        synchronized (this.lock) {
            if (!this.isContinue)
                this.interval = interval;
        }
    }

    public void stopClock() {
        synchronized (this.lock) {
            this.isContinue = false;
        }
    }

    @Override
    public void run() {
        super.run();
        this.isContinue = true;
        while (true) {
            synchronized (this.lock) {
                if (!this.isContinue)
                    break;
            }
            this.threadProc.processFunc();
            try {
                int itv;
                synchronized (this.lock) {
                    itv = interval;
                }
                Thread.sleep(itv);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
import org.bytedeco.javacpp.opencv_core.IplImage;
import org.bytedeco.javacv.FrameGrabber;
import org.bytedeco.javacv.OpenCVFrameConverter;
import org.bytedeco.javacv.OpenCVFrameGrabber;

import javax.imageio.ImageIO;
import javax.imageio.stream.MemoryCacheImageInputStream;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * Created by asus on 2017/4/1.
 */
public class picCaptureDialog extends JDialog implements ActionListener, ThreadProc, WindowListener {
    private JButton correctButton, cancelButton;
    private JLabel picLabel;
    private JPanel mainPanel;
    private FrameGrabber grabber = null;
    private OpenCVFrameConverter.ToIplImage converter = new OpenCVFrameConverter.ToIplImage();
    private ClockThread clockThread;
    private byte[] data = null;
    private byte[] rgbData = null;
    private Bitmap bitmap = null;
    private String filePath = null;

    public picCaptureDialog(JFrame parent) {
        super(parent,"自拍头像", true);
        init();
        setSize(800, 640);
        setLocationRelativeTo(null);
        addWindowListener(this);
        clockThread = new ClockThread(this, 30);
        try {
            initGrabber();
            clockThread.start();
            setVisible(true);
        } catch (FrameGrabber.Exception e) {
            e.printStackTrace();
            stopGrabber();
            dispose();
        }
    }

    public String getFilePath() {
        return filePath;
    }

    private void init() {
        add(getMainPanel());
    }

    private JPanel getMainPanel() {
        mainPanel = new JPanel();
        mainPanel.setLayout(null);
        picLabel = new JLabel();
        picLabel.setBounds(80, 25, 640, 480);
        picLabel.setBackground(new Color(164, 217, 248));
        picLabel.setOpaque(true);
        correctButton = new JButton("拍照");
        correctButton.setBounds(300, 520, 80, 30);
        correctButton.addActionListener(this);
        cancelButton = new JButton("取消");
        cancelButton.setBounds(420, 520, 80, 30);
        cancelButton.addActionListener(this);
        mainPanel.add(picLabel);
        mainPanel.add(correctButton);
        mainPanel.add(cancelButton);
        return mainPanel;
    }

    private void initGrabber() throws FrameGrabber.Exception {
        grabber = new OpenCVFrameGrabber(0);
        grabber.start();
    }

    private void stopGrabber() {
        if (grabber == null)
            return;
        try {
            if (clockThread.isAlive()) {
                clockThread.stopClock();
                try {
                    clockThread.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            grabber.stop();
        } catch (FrameGrabber.Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == correctButton) {
            if (clockThread.isAlive()) {
                clockThread.stopClock();
                try {
                    clockThread.join();
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
                correctButton.setText("保存照片");
                cancelButton.setText("重拍");
            } else {
                // 保存照片
                FileOutputStream fos = null;
                try {
                    filePath = new File("capture.bmp").getAbsolutePath();
                    fos = new FileOutputStream(filePath);
                    fos.write(bitmap.getImageBuffer());
                } catch (FileNotFoundException e1) {
                    e1.printStackTrace();
                } catch (IOException e1) {
                    e1.printStackTrace();
                } finally {
                    if (null != fos) {
                        try {
                            fos.close();
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                    }
                }

                stopGrabber();
                dispose();
            }
        }
        if (e.getSource() == cancelButton) {
            if (clockThread.isAlive()) {
                stopGrabber();
                dispose();
            } else {
                clockThread = new ClockThread(this, 30);
                clockThread.start();
                correctButton.setText("拍照");
                cancelButton.setText("取消");
            }
        }
    }

    @Override
    public void processFunc() {
        try {
            IplImage iplImage = converter.convert(grabber.grab());
            int width = iplImage.width();
            int height = iplImage.height();
            if (null == data) {
                int size = iplImage.imageSize();
                bitmap = new Bitmap(width, height);
                data = new byte[size];
                rgbData = new byte[size];
            }
            iplImage.imageData().get(data);
            int pitch = bitmap.getPitch();
            for (int i = 0; i < height; i++) {
                System.arraycopy(data, i * pitch,
                        rgbData, (height - i - 1) * pitch, pitch);
            }
            bitmap.setImageData(rgbData);
            BufferedImage bImage = ImageIO.read(new MemoryCacheImageInputStream(
                    new ByteArrayInputStream(bitmap.getImageBuffer())));
            ImageIcon image = new ImageIcon(Toolkit.getDefaultToolkit().createImage(bImage.getSource()));
            picLabel.setIcon(image);
        } catch (FrameGrabber.Exception e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void windowOpened(WindowEvent e) {
    }

    @Override
    public void windowClosing(WindowEvent e) {
        stopGrabber();
    }

    @Override
    public void windowClosed(WindowEvent e) {
    }
public interface ThreadProc {
    void processFunc();
}
@Override public void windowIconified(WindowEvent e) { } @Override public void windowDeiconified(WindowEvent e) { } @Override public void windowActivated(WindowEvent e) { } @Override public void windowDeactivated(WindowEvent e) { }}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值