zoukankan      html  css  js  c++  java
  • 添加头像


    import java.awt.Color;
    import java.awt.Image;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;

    import javax.swing.BorderFactory;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JLabel;

    public class NewFile extends JFrame{
      private JLabel jl = new JLabel();
      public NewFile(){
        this.setLayout(null);
        jl.setBounds(30, 30, 100, 150);
        jl.setBorder(BorderFactory.createLineBorder(Color.black));
        this.add(jl);

        JButton addButton = new JButton("添加头像");
        addButton.setBounds(30, 190, 100, 20);
        this.add(addButton);
        addButton.addActionListener(new ActionListener() {

          @Override
          public void actionPerformed(ActionEvent arg0) {
            JFileChooser jfc = new JFileChooser();
            int index = jfc.showOpenDialog(null);
            if(index == 0){
              File f = jfc.getSelectedFile();
              Image img = new ImageIcon(f.getAbsolutePath()).getImage();
              img = img.getScaledInstance(100, 150, 10);
              jl.setIcon(new ImageIcon(img));
              File fs = new File("image");
                if(fs.exists()==false){
                  fs.mkdir();
                }
              String fileName = System.currentTimeMillis()+f.getName().substring(f.getName().lastIndexOf("."));
              InputStream in = null;
              OutputStream out = null;

              try {
                in = new FileInputStream(f);
                out = new FileOutputStream("image/"+fileName);
                byte[] by = new byte[1024];
                int len = 0;
                while((len = in.read(by))!= -1){
                  out.write(by, 0, len);
                }
              } catch (Exception e) {
                e.printStackTrace();
              }finally{
                try {
                  out.close();
                  in.close();
                } catch (IOException e) {
                  e.printStackTrace();
                }
              }
            }

          }
         });
        this.setSize(400, 300);
        this.setVisible(true);
        this.setDefaultCloseOperation(3);
        this.setLocationRelativeTo(null);
      }
      public static void main(String[] args) {
        NewFile nf = new NewFile();
      }

    }

  • 相关阅读:
    mac重启nginx时报nginx.pid不存在的解决办法
    js 正则表达式
    js 闭包
    js yarn
    js npm
    vue3 vite
    node 错误处理
    node fs
    linux包管理工具使用和区别(转)
    MySQL数据库学习----理论基础
  • 原文地址:https://www.cnblogs.com/tcc89/p/5402502.html
Copyright © 2011-2022 走看看