二、JAVA調(diào)用悍趴桑康威視SDK實現(xiàn)攝像頭預(yù)覽完整版

接上一章:一谒臼、JAVA調(diào)用海康威視SDK實現(xiàn)攝像頭預(yù)覽

  1. 添加攝像頭信息輸入框
  2. 添加視頻控制按鈕
  3. 添加截圖功能

代碼:

  • PreView.java
package com.kx.hcws;

import javax.swing.JFrame;
import javax.swing.JPopupMenu;

import com.kx.hcws.sdk.HCNetSDK;
import com.kx.hcws.sdk.HCNetSDKManger;
import com.kx.hcws.ui.Player;

public class PreView {
    // private static String ip;
    // private static String username;
    // private static String password;

    public static void main(String[] args) {
        // 確保一個漂亮的外觀風(fēng)格
        JFrame.setDefaultLookAndFeelDecorated(true);
        JPopupMenu.setDefaultLightWeightPopupEnabled(false);// 防止被播放窗口(AWT組件)覆蓋

        // 顯示應(yīng)用 GUI
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                // 初始化阂铮康播放器
                HCNetSDKManger.init();
                HCNetSDK.INSTANCE.NET_DVR_Init();
                HCNetSDK.INSTANCE.NET_DVR_SetConnectTime(5000, 5);
                HCNetSDK.INSTANCE.NET_DVR_SetReconnect(1000, true);

                /*
                 * IP地址:攝像頭IP地址蜈缤。 用戶名:攝像頭登錄用戶名。 密碼:攝像頭驗證碼冯挎。 攝像頭編號:可以自定義底哥。
                 * 
                 * "192.168.2.18", "admin", "axjy123456", 8000, 1L
                 */
                new Player();
            }
        });
    }
}
  • HcPlayerPanel.java
package com.kx.hcws.ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;

import javax.swing.JOptionPane;
import javax.swing.JPanel;

import com.kx.hcws.sdk.HCNetSDK;
import com.kx.hcws.sdk.HCNetSDK.FExceptionCallBack;
import com.kx.hcws.sdk.HCNetSDKManger;
import com.kx.hcws.sdk.PlayCtrl;
import com.sun.jna.Native;
import com.sun.jna.NativeLong;
import com.sun.jna.Pointer;
import com.sun.jna.examples.win32.W32API.HWND;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.ptr.NativeLongByReference;

public class HcPlayerPanel extends JPanel {
    private static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(HcPlayerPanel.class);

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    // 播放控制
    private static PlayCtrl playControl = PlayCtrl.INSTANCE;

    private String m_sDeviceIP;
    private String username;
    private String password;
    private int port;
    private Long deviceId = 1L;

    private long iChannelNum;

    private boolean isplay = false;

    // 用戶參數(shù)
    private HCNetSDK.NET_DVR_CLIENTINFO m_strClientInfo;
    // 預(yù)覽句柄
    private NativeLong lPreviewHandle = new NativeLong(-1);
    // 播放界面
    public java.awt.Panel panelRealplay = new java.awt.Panel();
    public javax.swing.JPanel jPanelRealplayArea = new javax.swing.JPanel();
    // 設(shè)備指針
    private NativeLongByReference devicePoint;
    // 播放端口
    private NativeLongByReference m_lPort = new NativeLongByReference(new NativeLong(-1));
    // 異常回調(diào)
    private FExceptionCallBack exceptionCallBack = new FExceptionCallBack() {
        @Override
        public void invoke(int dwType, NativeLong lUserID, NativeLong lHandle, Pointer pUser) {
            NativeLong deviceid = pUser.getNativeLong(0);

            System.out.println("預(yù)覽異常:dwType=" + dwType + ",lUserID=" + lUserID + ",lHandle=" + lHandle + ",pUser="
                    + deviceid.intValue());

            // EXCEPTION_EXCHANGE = 0x8000;// 用戶交互時異常
            // EXCEPTION_AUDIOEXCHANGE = 0x8001;//語音對講異常
            // EXCEPTION_ALARM = 0x8002;// 報警異常
            // EXCEPTION_PREVIEW = 0x8003;// 網(wǎng)絡(luò)預(yù)覽異常
            // EXCEPTION_SERIAL = 0x8004;// 透明通道異常
            // EXCEPTION_RECONNECT = 0x8005; // 預(yù)覽時重連
            // EXCEPTION_ALARMRECONNECT = 0x8006;//報警時重連
            // EXCEPTION_SERIALRECONNECT = 0x8007;//透明通道重連
            // EXCEPTION_PLAYBACK = 0x8010;// 回放異常
            // EXCEPTION_DISKFMT = 0x8011;// 硬盤格式化
            if (dwType == HCNetSDK.EXCEPTION_ALARM || dwType == HCNetSDK.EXCEPTION_RECONNECT
                    || dwType == HCNetSDK.EXCEPTION_ALARMRECONNECT || dwType == HCNetSDK.EXCEPTION_SERIALRECONNECT
                    || dwType == HCNetSDK.EXCEPTION_PLAYBACK || dwType == 32971 || dwType == 32776 || dwType == 32789
                    || dwType == 32790 || dwType == 32791 || dwType == 32776 || dwType == 32793 || dwType == 32800
                    || dwType == 32804 || dwType == 32805 || dwType == 32832 || dwType == 32833 || dwType == 32834) {
                return;
            }
        }
    };

    public HcPlayerPanel() {
        init();
    }

    /**
     * 開始房官,傳入對應(yīng)參數(shù)
     * 
     * @param m_sDeviceIP
     * @param username
     * @param password
     * @param port
     * @param deviceId
     */
    public void start(String m_sDeviceIP, String username, String password, int port, Long deviceId) {
        this.m_sDeviceIP = m_sDeviceIP;
        this.username = username;
        this.password = password;
        this.port = port;
        this.deviceId = deviceId;
    }

    /**
     * 初始化組件
     */
    private void init() {
        panelRealplay.setBackground(Color.BLACK);
        jPanelRealplayArea.setBackground(Color.BLACK);
        javax.swing.GroupLayout panelRealplayLayout = new javax.swing.GroupLayout(panelRealplay);
        panelRealplay.setLayout(panelRealplayLayout);
        javax.swing.GroupLayout jPanelRealplayAreaLayout = new javax.swing.GroupLayout(jPanelRealplayArea);
        jPanelRealplayArea.setLayout(jPanelRealplayAreaLayout);
        jPanelRealplayAreaLayout.setHorizontalGroup(
                jPanelRealplayAreaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(
                        panelRealplay, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE,
                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE));
        jPanelRealplayAreaLayout.setVerticalGroup(jPanelRealplayAreaLayout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(panelRealplay,
                        javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE));
        devicePoint = new NativeLongByReference(new NativeLong(deviceId));// 設(shè)備編號

        panelRealplay.setPreferredSize(new Dimension(getWidth(), getHeight()));

        // 注冊異常信息
        HCNetSDKManger.hCNetSDK.NET_DVR_SetExceptionCallBack_V30(0, 0, exceptionCallBack, devicePoint.getPointer());
    }

    /**
     * 開始播放
     */
    public void play() {
        NativeLong lUserID = new NativeLong(-1);// 用戶句柄
        if (lUserID.longValue() > -1) {// 不注銷
            // 先注銷
            HCNetSDKManger.hCNetSDK.NET_DVR_Logout_V30(lUserID);
            lUserID = new NativeLong(-1);
        }
        // 注冊
        HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30();
        lUserID = HCNetSDKManger.hCNetSDK.NET_DVR_Login_V30(m_sDeviceIP, (short) port, username, password,
                m_strDeviceInfo);
        long userID = lUserID.longValue();
        if (userID == -1) {
            System.out.println(HCNetSDKManger.hCNetSDK.NET_DVR_GetLastError());
            System.out.println("設(shè)備注冊失斨夯铡:" + m_sDeviceIP + "--" + username + "--" + password + "--" + port);
            JOptionPane.showMessageDialog(this, "注冊失敗");
            return;
        } else {
            // CreateDeviceTree();
        }

        if (lUserID == null || lUserID.intValue() == -1) {
            logger.info("注冊失敗");
            return;
        }

        panelRealplay.setPreferredSize(new Dimension(getWidth(), getHeight()));
        removeAll();

        add(jPanelRealplayArea, BorderLayout.CENTER);
        revalidate();

        // 獲取窗口句柄
        HWND hwnd = new HWND(Native.getComponentPointer(panelRealplay));
        // 獲取通道號

        IntByReference ibrBytesReturned = new IntByReference(0);// 獲取IP接入配置參數(shù)
        boolean bRet = false;

        HCNetSDK.NET_DVR_IPPARACFG m_strIpparaCfg = new HCNetSDK.NET_DVR_IPPARACFG();
        m_strIpparaCfg.write();
        Pointer lpIpParaConfig = m_strIpparaCfg.getPointer();
        bRet = HCNetSDKManger.hCNetSDK.NET_DVR_GetDVRConfig(lUserID, HCNetSDK.NET_DVR_GET_IPPARACFG, new NativeLong(0),
                lpIpParaConfig, m_strIpparaCfg.size(), ibrBytesReturned);
        m_strIpparaCfg.read();

        // 設(shè)備支持IP通道
        String sChannelName = "";
        if (!bRet) {
            // 設(shè)備不支持,則表示沒有IP通道
            for (int iChannum = 0; iChannum < m_strDeviceInfo.byChanNum; iChannum++) {
                sChannelName = "Camera" + (iChannum + m_strDeviceInfo.byStartChan);
            }
        } else {
            // 設(shè)備支持IP通道
            for (int iChannum = 0; iChannum < m_strDeviceInfo.byChanNum; iChannum++) {
                if (m_strIpparaCfg.byAnalogChanEnable[iChannum] == 1) {
                    sChannelName = "Camera" + (iChannum + m_strDeviceInfo.byStartChan);
                }
            }
            for (int iChannum = 0; iChannum < HCNetSDK.MAX_IP_CHANNEL; iChannum++)
                if (m_strIpparaCfg.struIPChanInfo[iChannum].byEnable == 1) {
                    sChannelName = "IPCamera" + (iChannum + m_strDeviceInfo.byStartChan);
                }
        }
        iChannelNum = -1;
        if (sChannelName.charAt(0) == 'C') {// Camara開頭表示模擬通道
            // 子字符串中獲取通道號
            iChannelNum = Integer.parseInt(sChannelName.substring(6));
        } else {
            if (sChannelName.charAt(0) == 'I') {// IPCamara開頭表示IP通道,子字符創(chuàng)中獲取通道號,IP通道號要加32
                iChannelNum = Integer.parseInt(sChannelName.substring(8)) + 32;
            } else {
                logger.info("通道號獲取失敗");
                return;
            }
        }
        if (iChannelNum == -1) {
            logger.info("請選擇要預(yù)覽的通道");
            return;
        }

        m_strClientInfo = new HCNetSDK.NET_DVR_CLIENTINFO();
        m_strClientInfo.lChannel = new NativeLong(iChannelNum);
        m_strClientInfo.hPlayWnd = hwnd;
        lPreviewHandle = HCNetSDKManger.hCNetSDK.NET_DVR_RealPlay_V30(lUserID, m_strClientInfo, null, null, true);
        long previewSucValue = lPreviewHandle.longValue();
        // 預(yù)覽失敗時:
        if (previewSucValue == -1) {
            System.out.println("預(yù)覽失敗:" + HCNetSDKManger.hCNetSDK.NET_DVR_GetLastError());
            return;
        }
        System.out.println("預(yù)覽成功!");
        validate();
        isplay = true;
    }

    /**
     * 停止播放
     */
    public void stop() {
        logger.info("設(shè)備" + deviceId + "停止播放===================");
        if (lPreviewHandle != null && lPreviewHandle.longValue() != -1) {
            if (!HCNetSDKManger.hCNetSDK.NET_DVR_StopRealPlay(lPreviewHandle)) {
                logger.info("設(shè)備" + deviceId + "停止播放失敗");
            }
            if (m_lPort.getValue().intValue() != -1) {
                if (!playControl.PlayM4_Stop(m_lPort.getValue())) {
                    logger.info("設(shè)備" + deviceId + "停止播放失敗");
                }
                m_lPort.setValue(new NativeLong(-1));
            }
        }
        panelRealplay.repaint();
        isplay = false;
    }

    public boolean isIsplay() {
        return isplay;
    }

    /**
     * 實現(xiàn)截圖
     */
    public void snapshot(String filepath) {
        if (!HCNetSDKManger.hCNetSDK.NET_DVR_CapturePicture(lPreviewHandle, filepath)) {
            JOptionPane.showMessageDialog(this, "設(shè)備截屏失敗:" + HCNetSDKManger.hCNetSDK.NET_DVR_GetLastError());
            System.out.println("設(shè)備截屏失敗:" + HCNetSDKManger.hCNetSDK.NET_DVR_GetLastError());
        }else{
            JOptionPane.showMessageDialog(this, "截圖成功翰守!");
        }
    }
}
  • Player.java
package com.kx.hcws.ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class Player extends JFrame implements WindowListener {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    private HcPlayerPanel playerPanel;

    private JTextField ipField;
    private JTextField usernameField;
    private JPasswordField pwdField;

    public Player() {
        setSize(1200, 600);
        setResizable(true);
        setTitle("設(shè)備預(yù)覽");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 關(guān)閉窗口時關(guān)閉系統(tǒng)

        getContentPane().setLayout(new BorderLayout());

        playerPanel = new HcPlayerPanel();
        playerPanel.setBackground(Color.BLACK);
        playerPanel.setPreferredSize(new Dimension(1000, 600));

        getContentPane().add(playerPanel, BorderLayout.CENTER);

        initCtrlPanel();

        setVisible(true);
    }

    private void initCtrlPanel() {
        JPanel content = new JPanel();
        content.setLayout(new FlowLayout());

        {// IP
            JLabel jLabel = new JLabel("IP:");
            jLabel.setPreferredSize(new Dimension(60, 30));
            jLabel.setHorizontalTextPosition(JLabel.CENTER);
            jLabel.setVerticalAlignment(JLabel.CENTER);
            content.add(jLabel);

            ipField = new JTextField();
            ipField.setPreferredSize(new Dimension(130, 30));
            content.add(ipField);
        }

        {// 用戶名
            JLabel jLabel = new JLabel("用戶名:");
            jLabel.setPreferredSize(new Dimension(60, 30));
            jLabel.setHorizontalTextPosition(JLabel.CENTER);
            jLabel.setVerticalAlignment(JLabel.CENTER);
            content.add(jLabel);

            usernameField = new JTextField("admin");
            usernameField.setPreferredSize(new Dimension(130, 30));
            content.add(usernameField);
        }

        {// 密碼
            JLabel jLabel = new JLabel("密碼:");
            jLabel.setPreferredSize(new Dimension(60, 30));
            jLabel.setHorizontalTextPosition(JLabel.CENTER);
            jLabel.setVerticalAlignment(JLabel.CENTER);
            content.add(jLabel);

            pwdField = new JPasswordField("");
            pwdField.setPreferredSize(new Dimension(130, 30));
            content.add(pwdField);
        }

        {// 按鈕
            JButton playBtn = new JButton("播放");
            playBtn.setPreferredSize(new Dimension(150, 30));
            playBtn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    String m_sDeviceIP = ipField.getText();
                    if (m_sDeviceIP == null || "".equals(m_sDeviceIP)) {
                        JOptionPane.showMessageDialog(Player.this, "IP不能為空");
                        return;
                    }

                    String username = usernameField.getText();
                    if (username == null || "".equals(username)) {
                        JOptionPane.showMessageDialog(Player.this, "用戶名不能為空");
                        return;
                    }

                    String password = pwdField.getText();
                    if (password == null || "".equals(password)) {
                        JOptionPane.showMessageDialog(Player.this, "密碼不能為空");
                        return;
                    }

                    if (playerPanel.isIsplay()) {// 先停止
                        playerPanel.stop();
                    }
                    playerPanel.start(m_sDeviceIP, username, password, 8000, 1L);

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            playerPanel.play();
                        }
                    }).start();
                }
            });
            content.add(playBtn);

            JButton imgBtn = new JButton("截圖");
            imgBtn.setPreferredSize(new Dimension(150, 30));
            imgBtn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (!playerPanel.isIsplay()) {// 先停止
                        JOptionPane.showMessageDialog(Player.this, "請先預(yù)覽孵奶!");
                        return;
                    }
                    JFileChooser filechooser = new JFileChooser();// 創(chuàng)建文件選擇器
                    filechooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                    int returnVal = filechooser.showOpenDialog(Player.this);
                    if (returnVal == JFileChooser.APPROVE_OPTION) {
                        String file = filechooser.getSelectedFile().getAbsolutePath() + "\\" + new Date().getTime()
                                + ".jpg";
                        playerPanel.snapshot(file);
                    }
                }
            });
            content.add(imgBtn);
        }

        content.setPreferredSize(new Dimension(200, 600));

        getContentPane().add(content, BorderLayout.WEST);
    }

    @Override
    public void windowActivated(WindowEvent e) {

    }

    @Override
    public void windowClosed(WindowEvent e) {
    }

    @Override
    public void windowClosing(WindowEvent e) {
        playerPanel.stop();
    }

    @Override
    public void windowDeactivated(WindowEvent e) {

    }

    @Override
    public void windowDeiconified(WindowEvent e) {

    }

    @Override
    public void windowIconified(WindowEvent e) {

    }

    @Override
    public void windowOpened(WindowEvent e) {

    }
}

預(yù)覽:

20210702213201779.png
20210702213227612.png
20210702213253109.png
20210702213308914.png

源碼:源碼下載

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市蜡峰,隨后出現(xiàn)的幾起案子了袁,更是在濱河造成了極大的恐慌,老刑警劉巖湿颅,帶你破解...
    沈念sama閱讀 211,290評論 6 491
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件载绿,死亡現(xiàn)場離奇詭異,居然都是意外死亡油航,警方通過查閱死者的電腦和手機卢鹦,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,107評論 2 385
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人冀自,你說我怎么就攤上這事∶肜玻” “怎么了熬粗?”我有些...
    開封第一講書人閱讀 156,872評論 0 347
  • 文/不壞的土叔 我叫張陵,是天一觀的道長余境。 經(jīng)常有香客問我驻呐,道長,這世上最難降的妖魔是什么芳来? 我笑而不...
    開封第一講書人閱讀 56,415評論 1 283
  • 正文 為了忘掉前任含末,我火速辦了婚禮,結(jié)果婚禮上即舌,老公的妹妹穿的比我還像新娘佣盒。我一直安慰自己,他們只是感情好顽聂,可當我...
    茶點故事閱讀 65,453評論 6 385
  • 文/花漫 我一把揭開白布肥惭。 她就那樣靜靜地躺著,像睡著了一般紊搪。 火紅的嫁衣襯著肌膚如雪蜜葱。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,784評論 1 290
  • 那天耀石,我揣著相機與錄音牵囤,去河邊找鬼。 笑死滞伟,一個胖子當著我的面吹牛揭鳞,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播诗良,決...
    沈念sama閱讀 38,927評論 3 406
  • 文/蒼蘭香墨 我猛地睜開眼汹桦,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了鉴裹?” 一聲冷哼從身側(cè)響起舞骆,我...
    開封第一講書人閱讀 37,691評論 0 266
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎径荔,沒想到半個月后督禽,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,137評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡总处,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,472評論 2 326
  • 正文 我和宋清朗相戀三年狈惫,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,622評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡胧谈,死狀恐怖忆肾,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情菱肖,我是刑警寧澤客冈,帶...
    沈念sama閱讀 34,289評論 4 329
  • 正文 年R本政府宣布,位于F島的核電站稳强,受9級特大地震影響场仲,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜退疫,卻給世界環(huán)境...
    茶點故事閱讀 39,887評論 3 312
  • 文/蒙蒙 一渠缕、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧褒繁,春花似錦亦鳞、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,741評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至俊抵,卻和暖如春谁不,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背徽诲。 一陣腳步聲響...
    開封第一講書人閱讀 31,977評論 1 265
  • 我被黑心中介騙來泰國打工刹帕, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人谎替。 一個月前我還...
    沈念sama閱讀 46,316評論 2 360
  • 正文 我出身青樓偷溺,卻偏偏與公主長得像,于是被迫代替她去往敵國和親钱贯。 傳聞我的和親對象是個殘疾皇子挫掏,可洞房花燭夜當晚...
    茶點故事閱讀 43,490評論 2 348

推薦閱讀更多精彩內(nèi)容