使用Webcam完成拍照功能

结构比较简单,只需要三个包。自行百度

 代码:

package com.company;

import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamPanel;
import com.github.sarxos.webcam.WebcamUtils;


import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;

public class MainClass {

    public static String photoName = "";

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

    private static void getCamera() {
        final Webcam webcam = Webcam.getDefault();
        if (webcam.isOpen()) {
            webcam.close();
        }
        // 设置显示窗口大小
        webcam.setViewSize(WebcamResolution.VGA.getSize());
        // 设置分辨率大小,WebcamResolution 这个类是自己写的,和jar里的一样,只是自定义了分辨率而已。注意的是,如果分辨率过大,会把上面设置的窗口撑大
        webcam.getDevice().setResolution(WebcamResolution.WSVGA2.getSize());

        WebcamPanel panel = new WebcamPanel(webcam);
        panel.setFPSDisplayed(true);
        panel.setDisplayDebugInfo(true);
        panel.setImageSizeDisplayed(true);
        JFrame window = new JFrame("拍照");
        window.add(panel);
        window.setResizable(true);
        window.setDefaultCloseOperation(1);
        window.pack();
        window.setVisible(true);
        final JButton button = new JButton("拍照");
        window.add(panel, "Center");
        window.add(button, "South");
        window.setResizable(true);
        window.pack();
        window.setVisible(true);
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                button.setEnabled(false);
                File directory = new File("..");
                String pf = null;
                try {
                    pf = directory.getCanonicalPath().substring(0,1);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                Calendar cal = Calendar.getInstance();
                int year = cal.get(Calendar.YEAR);
                int month = cal.get(Calendar.MONTH) + 1;
                photoName = pf+":\\pic\\"+year+"\\"+month+"月" ;
                mkdir(photoName);
                String path = photoName+ "\\"+ System.currentTimeMillis();
                WebcamUtils.capture(webcam,path, "PNG");
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        String imageBase = ImageUtil.getImageStr1(path + "." + "PNG".toLowerCase());
                        // 做个简单的弹窗
                        if (null != imageBase){
                            javaAlert("拍照成功!");
                        }else {
                            javaAlert("拍照失败!");
                        }
                        button.setEnabled(true);
                    }
                });
            }
        });
    }

    /**
     * 创建文件夹
     * @param path
     */
    public static void mkdir(String path) {
        File fd = null;
        try {
            fd = new File(path);
            if (!fd.exists()) {
                fd.mkdirs();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            fd = null;
        }
    }

    /**
     * 简单的弹窗
     * @param param
     */
    public static void javaAlert( String param) {
        JOptionPane.showMessageDialog(null,  param,"",
                JOptionPane.ERROR_MESSAGE);
    }
}

工具类:

package com.company;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;

public class ImageUtil {
   
   /**
    * 将base64编码字符串转换为图片
    * @param imgStr base64编码字符串
    * @param path 图片路径-具体到文件
    * @return boolean
    */
   public static boolean generateImage(String imgStr, String path) {
      if(imgStr == null)
         return false;
      BASE64Decoder decoder = new BASE64Decoder();
      try{
         byte[] b = decoder.decodeBuffer(imgStr);
         for (int i = 0;i<b.length;++i){
            if(b[i]<0)
               b[i]+=256;
         }
         OutputStream out = new FileOutputStream(path);
         out.write(b);
         out.flush();
         out.close();
         return true;
      } catch (IOException e) {
         e.printStackTrace();
         return false;
      }
   }
   
   /**
    * 根据图片地址转换为base64编码字符串
    * @param imgFile 文件路径
    * @return base64字符串
    */
   public static String getImageStr(String imgFile) {
      InputStream inputStream = null;
      byte[] data = null;
      try {
         inputStream = new FileInputStream(imgFile);
         data = new byte[inputStream.available()];
         inputStream.read(data);
         inputStream.close();
      } catch (IOException e) {
         e.printStackTrace();
      }
      BASE64Encoder encoder = new BASE64Encoder();
      return encoder.encode(data);
   }

   public static String getImageStr1(String imgFile) {
      InputStream inputStream = null;
      byte[] data = null;
      File file = new File(imgFile);

      try {
         inputStream = new FileInputStream(file.getCanonicalPath());
         data = new byte[inputStream.available()];
         inputStream.read(data);
         inputStream.close();
      } catch (IOException var5) {
         var5.printStackTrace();
      }

      BASE64Encoder encoder = new BASE64Encoder();
      return encoder.encode(data);
   }
// public static void main(String[] args) {
//    String imgBase64 = getImageStr("D:/appointEdit_V4.0/preview/1558084092554/干部任免审批表_赵文杰_1.png");
//    System.out.println(imgBase64);
// }
   
}

自定义类:

package com.company;

import java.awt.*;

/**
 * @date 2021/7/20 16:33
 */
public enum WebcamResolution {
    QQVGA(176, 144),
    HQVGA(240, 160),
    QVGA(320, 240),
    WQVGA(400, 240),
    HVGA(480, 320),
    VGA(640, 480),
    WVGA(768, 480),
    FWVGA(854, 480),
    SVGA(800, 600),
    DVGA(960, 640),
    WSVGA1(1024, 576),
//    WSVGA2(1024, 600),
    WSVGA2(1300, 900),
    XGA(1024, 768),
    XGAP(1152, 864),
    WXGA1(1366, 768),
    WXGA2(1280, 800),
    WXGAP(1440, 900),
    SXGA(1280, 1024),
    SXGAP(1400, 1050),
    WSXGAP(1680, 1050),
    UXGA(1600, 1200),
    WUXGA(1920, 1200),
    QWXGA(2048, 1152),
    QXGA(2048, 1536),
    WQXGA(2560, 1600),
    QSXGA(2560, 2048),
    WQSXGA(3200, 2048),
    QUXGA(3200, 2400),
    WQUXGA(3840, 2400),
    HXGA(4096, 3072),
    WHXGA(5120, 3200),
    HSXGA(5120, 4096),
    WHSXGA(6400, 4096),
    HUXGA(6400, 4800),
    WHUXGA(7680, 4800),
    NHD(640, 360),
    QHD(960, 540),
    HD(1280, 720),
    HDP(1600, 900),
    FHD(1920, 1080),
    FHDP(2160, 1440),
    DCI2K(2048, 1080),
    WQHD(2560, 1440),
    WQHDP(3200, 1800),
    UWQHD(3440, 1440),
    UW4K(3840, 1600),
    UHD4K(3840, 3160),
    DCI4K(4096, 2160),
    UW5K(5120, 2160),
    UHDP5K(5120, 2880),
    UW8K(7680, 3200),
    UHD8K(7680, 4320),
    PAL(768, 576),
    CIF(352, 288);

    private Dimension size = null;

    private WebcamResolution(int width, int height) {
        this.size = new Dimension(width, height);
    }

    public Dimension getSize() {
        return this.size;
    }

    public int getPixelsCount() {
        return this.size.width * this.size.height;
    }

    public Dimension getAspectRatio() {
        int factor = this.getCommonFactor(this.size.width, this.size.height);
        int wr = this.size.width / factor;
        int hr = this.size.height / factor;
        return new Dimension(wr, hr);
    }

    private int getCommonFactor(int width, int height) {
        return height == 0 ? width : this.getCommonFactor(height, width % height);
    }

    public int getWidth() {
        return this.size.width;
    }

    public int getHeight() {
        return this.size.height;
    }

    public String toString() {
        int w = this.size.width;
        int h = this.size.height;
        Dimension ratio = this.getAspectRatio();
        int rw = ratio.width;
        int rh = ratio.height;
        return super.toString() + ' ' + w + 'x' + h + " (" + rw + ':' + rh + ')';
    }

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

下载地址:

https://download.csdn.net/download/qq_30299243/20600771

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值