海康威视相机SDK二次开发(JAVA语言)

目录

      • 前言
      • 客户端创建虚拟相机
      • 示例代码
        • 保存图片程序
        • 运行结果
        • 修改需求
      • 二次开发
        • 引入外部包
        • 对SaveImage.java文件进行修改
          • 保存图片saveDataToFile方法
          • 选择相机chooseCamera方法
          • 主方法
        • FileUtil类处理过期照片
        • 启动类与配置文件
          • application.yml
          • 通过实体类读取yml
          • 启动类
        • SaveImage.java类全部代码
      • 运行结果

前言

有个项目需要使用java程序读取海康威视的相机图片。相机通过以太网连接服务器,部署在服务器上的java程序将相机拍摄的画面保存在指定路径下。
海康威视提供了sdk开发包,可以在官网中下载,windows和linux系统都有。但是开发包中给出的示例代码,无法满足实际需要,所以还需要对代码进行二次开发。
在进行二次开发时,官网并未提供java语言的开发手册,示例代码中也并未提供详细注释,所以我只能在阅读示例代码时,按照自己的理解添加一些注释。

客户端创建虚拟相机

实体相机已经还回去了,所以这里用MVS客户端创建一个虚拟相机,测试代码。
在这里插入图片描述
在这里插入图片描述

设置相机名字

在这里插入图片描述

示例代码

我这里只需要对保存照片的代码进行修改。
以下是官网提供的保存照片的代码
我在示例代码中对一些方法做了注释

保存图片程序
/**************************************************************************************************** @file      SaveImage.java* @breif     Use functions provided in MvCameraControlWrapper.jar to save image as JPEG。* @author    zhanglei72* @date      2020/02/10** @warning  * @version   V1.0.0  2020/02/10 Create this file* @since     2020/02/10**************************************************************************************************/import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;import MvCameraControlWrapper.*;
import static MvCameraControlWrapper.MvCameraControl.*;
import static MvCameraControlWrapper.MvCameraControlDefines.*;public class SaveImage
{/*** 打印连接的设备信息* 如果是通过以太网连接的相机,则会输出ip、名称等内容* 如果是通过usb连接的相机,则会输出相机名称*/private static void printDeviceInfo(MV_CC_DEVICE_INFO stDeviceInfo) {if (null == stDeviceInfo) {System.out.println("stDeviceInfo is null");return;}if (stDeviceInfo.transportLayerType == MV_GIGE_DEVICE) {System.out.println("\tCurrentIp:       " + stDeviceInfo.gigEInfo.currentIp);System.out.println("\tModel:           " + stDeviceInfo.gigEInfo.modelName);System.out.println("\tUserDefinedName: " + stDeviceInfo.gigEInfo.userDefinedName);} else if (stDeviceInfo.transportLayerType == MV_USB_DEVICE) {System.out.println("\tUserDefinedName: " + stDeviceInfo.usb3VInfo.userDefinedName);System.out.println("\tSerial Number:   " + stDeviceInfo.usb3VInfo.serialNumber);System.out.println("\tDevice Number:   " + stDeviceInfo.usb3VInfo.deviceNumber);} else {System.err.print("Device is not supported! \n");}System.out.println("\tAccessible:      "+ MvCameraControl.MV_CC_IsDeviceAccessible(stDeviceInfo, MV_ACCESS_Exclusive));System.out.println("");}private static void printFrameInfo(MV_FRAME_OUT_INFO stFrameInfo){if (null == stFrameInfo){System.err.println("stFrameInfo is null");return;}StringBuilder frameInfo = new StringBuilder("");frameInfo.append(("\tFrameNum[" + stFrameInfo.frameNum + "]"));frameInfo.append("\tWidth[" + stFrameInfo.width + "]");frameInfo.append("\tHeight[" + stFrameInfo.height + "]");frameInfo.append(String.format("\tPixelType[%#x]", stFrameInfo.pixelType.getnValue()));System.out.println(frameInfo.toString());}/*** 保存图片到本地* 这个方法中主要是设置了文件保存的路径*/public static void saveDataToFile(byte[] dataToSave, int dataSize, String fileName){OutputStream os = null;try{// Create directoryFile tempFile = new File("dat");if (!tempFile.exists()) {tempFile.mkdirs();}os = new FileOutputStream(tempFile.getPath() + File.separator + fileName);os.write(dataToSave, 0, dataSize);System.out.println("SaveImage succeed.");}catch (IOException e){e.printStackTrace();}finally{// Close file streamtry {os.close();} catch (IOException e) {e.printStackTrace();}}}/*** 当有多个相机连接但程序只能保存一台相机拍摄的照片* 所以需要通过此方法输入相机索引号*/public static int chooseCamera(ArrayList<MV_CC_DEVICE_INFO> stDeviceList){if (null == stDeviceList){return -1;}// Choose a device to operateint camIndex = -1;Scanner scanner = new Scanner(System.in);while (true){try{/** 手动输入*/System.out.print("Please input camera index (-1 to quit):");camIndex = scanner.nextInt();if ((camIndex >= 0 && camIndex < stDeviceList.size()) || -1 == camIndex){break;}else{System.out.println("Input error: " + camIndex);}}catch (Exception e){e.printStackTrace();camIndex = -1;break;}}scanner.close();if (-1 == camIndex){System.out.println("Bye.");return camIndex;}if (0 <= camIndex && stDeviceList.size() > camIndex){if (MV_GIGE_DEVICE == stDeviceList.get(camIndex).transportLayerType){System.out.println("Connect to camera[" + camIndex + "]: " + stDeviceList.get(camIndex).gigEInfo.userDefinedName);}else if (MV_USB_DEVICE == stDeviceList.get(camIndex).transportLayerType){System.out.println("Connect to camera[" + camIndex + "]: " + stDeviceList.get(camIndex).usb3VInfo.userDefinedName);}else{System.out.println("Device is not supported.");}}else{System.out.println("Invalid index " + camIndex);camIndex = -1;}return camIndex;}/*** 主方法* 保存照片的代码在这里*/public static void main(String[] args){int nRet = MV_OK;int camIndex = -1;Handle hCamera = null;ArrayList<MV_CC_DEVICE_INFO> stDeviceList;do{System.out.println("SDK Version " + MvCameraControl.MV_CC_GetSDKVersion());// Enuerate GigE and USB devices try{stDeviceList = MV_CC_EnumDevices(MV_GIGE_DEVICE | MV_USB_DEVICE);if (0 >= stDeviceList.size()){System.out.println("No devices found!");break;}int i = 0;for (MV_CC_DEVICE_INFO stDeviceInfo : stDeviceList){System.out.println("[camera " + (i++) + "]");printDeviceInfo(stDeviceInfo);}}catch (CameraControlException e){System.err.println("Enumrate devices failed!" + e.toString());e.printStackTrace();break;}// choose cameracamIndex = chooseCamera(stDeviceList);if (camIndex == -1){break;}// Create handletry{hCamera = MvCameraControl.MV_CC_CreateHandle(stDeviceList.get(camIndex));}catch (CameraControlException e){System.err.println("Create handle failed!" + e.toString());e.printStackTrace();hCamera = null;break;}// Open devicenRet = MvCameraControl.MV_CC_OpenDevice(hCamera);if (MV_OK != nRet){System.err.printf("Connect to camera failed, errcode: [%#x]\n", nRet);break;}// Make sure that trigger mode is off/** 设置相机的触发器开关 Off On*/nRet = MvCameraControl.MV_CC_SetEnumValueByString(hCamera, "TriggerMode", "Off");if (MV_OK != nRet){System.err.printf("SetTriggerMode failed, errcode: [%#x]\n", nRet);break;}// Get payload sizeMVCC_INTVALUE stParam = new MVCC_INTVALUE();nRet = MvCameraControl.MV_CC_GetIntValue(hCamera, "PayloadSize", stParam);if (MV_OK != nRet){System.err.printf("Get PayloadSize fail, errcode: [%#x]\n", nRet);break;}// Start grabbingnRet = MvCameraControl.MV_CC_StartGrabbing(hCamera);if (MV_OK != nRet){System.err.printf("Start Grabbing fail, errcode: [%#x]\n", nRet);break;}// Get one frameMV_FRAME_OUT_INFO stImageInfo = new MV_FRAME_OUT_INFO();byte[] pData = new byte[(int)stParam.curValue];nRet = MvCameraControl.MV_CC_GetOneFrameTimeout(hCamera, pData, stImageInfo, 1000);if (MV_OK != nRet){System.err.printf("GetOneFrameTimeout fail, errcode:[%#x]\n", nRet);break;}System.out.println("GetOneFrame: ");printFrameInfo(stImageInfo);int imageLen = stImageInfo.width * stImageInfo.height * 3;    // Every RGB pixel takes 3 bytesbyte[] imageBuffer = new byte[imageLen];// Call MV_CC_SaveImage to save image as JPEGMV_SAVE_IMAGE_PARAM stSaveParam = new MV_SAVE_IMAGE_PARAM();stSaveParam.width = stImageInfo.width;                                  // image widthstSaveParam.height = stImageInfo.height;                                // image heightstSaveParam.data = pData;                                               // image datastSaveParam.dataLen = stImageInfo.frameLen;                             // image data lengthstSaveParam.pixelType = stImageInfo.pixelType;                          // image pixel formatstSaveParam.imageBuffer = imageBuffer;                                  // output image bufferstSaveParam.imageType = MV_SAVE_IAMGE_TYPE.MV_Image_Jpeg;               // output image pixel formatstSaveParam.methodValue = 0;                                            // Interpolation method that converts Bayer format to RGB24.  0-Neareast 1-double linear 2-HamiltonstSaveParam.jpgQuality = 60;                                            // JPG endoding quality(50-99]nRet = MvCameraControl.MV_CC_SaveImage(hCamera, stSaveParam);if (MV_OK != nRet){System.err.printf("SaveImage fail, errcode: [%#x]\n", nRet);break;}// Save buffer content to file/** 将照片保存在本地,且在这里指定文件的名称*/saveDataToFile(imageBuffer, stSaveParam.imageLen, "SaveImage.jpeg");// Stop grabbingnRet = MvCameraControl.MV_CC_StopGrabbing(hCamera);if (MV_OK != nRet){System.err.printf("StopGrabbing fail, errcode: [%#x]\n", nRet);break;}} while (false);if (null != hCamera){// Destroy handlenRet = MvCameraControl.MV_CC_DestroyHandle(hCamera);if (MV_OK != nRet) {System.err.printf("DestroyHandle failed, errcode: [%#x]\n", nRet);}}}
}
运行结果

在这里插入图片描述
程序启动后,在控制台输出可连接的所有相机,用户输入相机索引号连接指定相机。[Camera 0]表示索引号为0。然后相机自动进行拍摄。
在这里插入图片描述

修改需求

通过运行程序,发现直接使用示例代码,无法满足实际使用需求。无法做到,图片保存名称不重复、图片保存路径无法自定义、需要用户手动输入相机索引号、对于指定日期以前的旧照片删除等等。

二次开发

首先记录对核心代码的修改内容,然后再将所有代码都列出来。
我这里使用了Springboot框架,为的是通过application.yml文件配置路径等数量,另外使用maven架构,方便打包。
在这里插入图片描述

SaveImage为核心代码类
FileUtil用来删除过期照片
ApplicationYml用来读取yml文件中的配置

引入外部包

在进行二次开发前,还需要引入官网提供的下载包。
在这里插入图片描述
创建lib文件夹,将jar放入后,右击,Add as library。
在pom.xml文件中引入依赖

    <dependencies><dependency><groupId>com.hzx.testmaven34hikvision</groupId><artifactId>MvCameraControlWrapper</artifactId><version>1.0</version><scope>system</scope><systemPath>${project.basedir}/lib/MvCameraControlWrapper.jar</systemPath></dependency></dependencies>
<build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><version>2.3.0.RELEASE</version><configuration><fork>true</fork><includeSystemScope>true</includeSystemScope></configuration></plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-surefire-plugin</artifactId><configuration><skip>true</skip></configuration></plugin></plugins>
</build>
对SaveImage.java文件进行修改

这里先对照着示例代码,将修改的地方列举出来。全部代码后面给出。
示例代码中一些无关紧要的输出内容,在二次开发时注释掉了,这里就不再详细说明。
修改的地方,通过注释标出

保存图片saveDataToFile方法
    public static void saveDataToFile(byte[] dataToSave, int dataSize, String fileName,String savePath) {OutputStream os = null;try {// Create directory/** savePath参数为图片保存路径,在调用方法时通过参数传入*/File tempFile = new File(savePath);if (!tempFile.exists()) {tempFile.mkdirs();}os = new FileOutputStream(tempFile.getPath() + File.separator + fileName);os.write(dataToSave, 0, dataSize);/** 图片保存成功后,输出当前时间*/System.out.println("--- " + sfTime.format(new Date()) + " Save Image succeed ---");} catch (IOException e) {e.printStackTrace();} finally {// Close file streamtry {os.close();} catch (IOException e) {e.printStackTrace();}}}
选择相机chooseCamera方法
    public static int chooseCamera(ArrayList<MV_CC_DEVICE_INFO> stDeviceList,int camIndex) {if (null == stDeviceList) {return -1;}// Choose a device to operate//int camIndex = -1;Scanner scanner = new Scanner(System.in);while (true) {try {/** 原本需要用户输入的camIndex(相机索引),修改为调用方法时传参* 实际值从yml文件中获取*///System.out.print("Please input camera index (-1 to quit):");//camIndex = scanner.nextInt();//camIndex = 1;if ((camIndex >= 0 && camIndex < stDeviceList.size()) || -1 == camIndex) {// System.out.println("自动连接 [camera 0]");break;} else {System.out.println("Input error: " + camIndex);camIndex=-1;break;}} catch (Exception e) {e.printStackTrace();camIndex = -1;break;}}scanner.close();/*** 未修改代码省略*/}
主方法

这里已经不是main方法了,因为使用springboot所以有了StartApplication类

    public static void mainImage(String savePath,Integer deleteDay,int camIndex) {int nRet = MV_OK;// int camIndex = -1;Handle hCamera = null;ArrayList<MV_CC_DEVICE_INFO> stDeviceList;boolean needConnectDevice = true;do {// Make sure that trigger mode is off/** 设置拍照触发器开关 出发模式需要到mvs客户端中为相机设置* 这里需要把MvCameraControl.MV_CC_SetEnumValueByString()方法第三个参数从Off改为On*/nRet = MvCameraControl.MV_CC_SetEnumValueByString(hCamera, "TriggerMode", "On");if (MV_OK != nRet) {System.err.printf("SetTriggerMode failed, errcode: [%#x]\n", nRet);break;}nRet = MvCameraControl.MV_CC_SaveImage(hCamera, stSaveParam);if (MV_OK != nRet) {//System.err.printf("SaveImage fail, errcode: [%#x]\n", nRet);// System.out.println(sfTime.format(new Date())+" "+ nRet + " No Image Need Save...");// break;//continue;} else {// 保存照片的方法 Save buffer content to file/*** 在这里设置照片的保存路径*/String savePathFull = savePath+ sfSave.format(new Date())+"/"+"camera"+camIndex+"/";saveDataToFile(imageBuffer, stSaveParam.imageLen, "SaveImage-" + sfSecond.format(new Date())+ ".jpeg",savePathFull);/* * 有新图片保存时,删除X天前保存图片的文件夹* X的实际值,通过参数传入*/Calendar calendar = Calendar.getInstance();calendar.setTime(new Date());// X天前的日期calendar.add(Calendar.DATE,(-deleteDay));String deleteFile = savePath+sfSave.format(calendar.getTime())+"/";FileUtil.deleteAllFile(deleteFile);}} while (true);}
FileUtil类处理过期照片

这里使用递归,删除保存的照片

public class FileUtil {public static void deleteAllFile(String dir){File dirFile = new File(dir);// 判断dir是否是目录且dir是否存在if (!dirFile.exists()||(!dirFile.isDirectory())) {// System.out.println("目录:"+dir+" 不存在");return;}// 删除文件夹中所有的文件,包括子文件夹File[] files = dirFile.listFiles();for (int i = 0; i < files.length; i++) {if (files[i].isFile()) {// 如果是文件直接删除files[i].delete();}else if(files[i].isDirectory()){// 如果是目录,则通过递归删除deleteAllFile(files[i].getAbsolutePath());}}// 最后删除当前文件夹dirFile.delete();}
}
启动类与配置文件
application.yml
config-info:image: D:/JavaCode/testmaven34hikvision/catch-image/ #图片保存路径deleteDay: 3 #删除X天前的图片connectCamera: 0 #连接相机编号
通过实体类读取yml
@ConfigurationProperties(prefix = "config-info")
@Component
public class ApplicationYml {private String image;private String deleteDay;private String connectCamera;public ApplicationYml() {}public String getImage() {return image;}public void setImage(String image) {this.image = image;}public String getDeleteDay() {return deleteDay;}public void setDeleteDay(String deleteDay) {this.deleteDay = deleteDay;}public String getConnectCamera() {return connectCamera;}public void setConnectCamera(String connectCamera) {this.connectCamera = connectCamera;}
}
启动类
@SpringBootApplication
@EnableConfigurationProperties
public class StartImage {private static ApplicationYml applicationYml;@Autowiredpublic void setApplicationYml(ApplicationYml applicationYml) {this.applicationYml = applicationYml;}public static void main(String[] args) throws Exception {SpringApplication.run(StartImage.class, args);System.out.println("image: "+applicationYml.getImage());System.out.println("deleteDay: "+applicationYml.getDeleteDay());System.out.println("camera: "+applicationYml.getConnectCamera());String image = applicationYml.getImage();SaveImage.mainImage(image,Integer.valueOf(applicationYml.getDeleteDay()),Integer.valueOf(applicationYml.getConnectCamera()));}
}
SaveImage.java类全部代码
public class SaveImage {private static SimpleDateFormat sfSecond = new SimpleDateFormat("yyyy-M-d_HH-mm-dd-SSS");private static SimpleDateFormat sfTime = new SimpleDateFormat("HH:mm:ss");private static SimpleDateFormat sfSave = new SimpleDateFormat("yyyy-M-d");private static void printDeviceInfo(MV_CC_DEVICE_INFO stDeviceInfo) {if (null == stDeviceInfo) {System.out.println("stDeviceInfo is null");return;}if (stDeviceInfo.transportLayerType == MV_GIGE_DEVICE) {System.out.println("\tCurrentIp:       " + stDeviceInfo.gigEInfo.currentIp);System.out.println("\tModel:           " + stDeviceInfo.gigEInfo.modelName);System.out.println("\tUserDefinedName: " + stDeviceInfo.gigEInfo.userDefinedName);} else if (stDeviceInfo.transportLayerType == MV_USB_DEVICE) {System.out.println("\tUserDefinedName: " + stDeviceInfo.usb3VInfo.userDefinedName);System.out.println("\tSerial Number:   " + stDeviceInfo.usb3VInfo.serialNumber);System.out.println("\tDevice Number:   " + stDeviceInfo.usb3VInfo.deviceNumber);} else {System.err.print("Device is not supported! \n");}System.out.println("\tAccessible:      " + MvCameraControl.MV_CC_IsDeviceAccessible(stDeviceInfo, MV_ACCESS_Exclusive));System.out.println("");}private static void printFrameInfo(MV_FRAME_OUT_INFO stFrameInfo) {if (null == stFrameInfo) {System.err.println("stFrameInfo is null");return;}StringBuilder frameInfo = new StringBuilder("");frameInfo.append(("\tFrameNum[" + stFrameInfo.frameNum + "]"));frameInfo.append("\tWidth[" + stFrameInfo.width + "]");frameInfo.append("\tHeight[" + stFrameInfo.height + "]");frameInfo.append(String.format("\tPixelType[%#x]", stFrameInfo.pixelType.getnValue()));// System.out.println(frameInfo.toString());}public static void saveDataToFile(byte[] dataToSave, int dataSize, String fileName,String savePath) {OutputStream os = null;try {// Create directory//File tempFile = new File(imagePathFun());File tempFile = new File(savePath);if (!tempFile.exists()) {tempFile.mkdirs();}os = new FileOutputStream(tempFile.getPath() + File.separator + fileName);os.write(dataToSave, 0, dataSize);System.out.println("--- " + sfTime.format(new Date()) + " Save Image succeed ---");} catch (IOException e) {e.printStackTrace();} finally {// Close file streamtry {os.close();} catch (IOException e) {e.printStackTrace();}}}public static int chooseCamera(ArrayList<MV_CC_DEVICE_INFO> stDeviceList,int camIndex) {if (null == stDeviceList) {return -1;}// Choose a device to operate//int camIndex = -1;Scanner scanner = new Scanner(System.in);while (true) {try {//System.out.print("Please input camera index (-1 to quit):");//camIndex = scanner.nextInt();//camIndex = 1;if ((camIndex >= 0 && camIndex < stDeviceList.size()) || -1 == camIndex) {// System.out.println("自动连接 [camera 0]");break;} else {System.out.println("Input error: " + camIndex);camIndex=-1;break;}} catch (Exception e) {e.printStackTrace();camIndex = -1;break;}}scanner.close();if (-1 == camIndex) {System.out.println("Bye.");return camIndex;}if (0 <= camIndex && stDeviceList.size() > camIndex) {if (MV_GIGE_DEVICE == stDeviceList.get(camIndex).transportLayerType) {System.out.println("Connect to camera[" + camIndex + "]: " + stDeviceList.get(camIndex).gigEInfo.userDefinedName);} else if (MV_USB_DEVICE == stDeviceList.get(camIndex).transportLayerType) {System.out.println("Connect to camera[" + camIndex + "]: " + stDeviceList.get(camIndex).usb3VInfo.userDefinedName);} else {System.out.println("Device is not supported.");}} else {System.out.println("Invalid index " + camIndex);camIndex = -1;}return camIndex;}public static void mainImage(String savePath,Integer deleteDay,int camIndex) {int nRet = MV_OK;// int camIndex = -1;Handle hCamera = null;ArrayList<MV_CC_DEVICE_INFO> stDeviceList;boolean needConnectDevice = true;do {if (needConnectDevice) {System.out.println("SDK Version " + MvCameraControl.MV_CC_GetSDKVersion());// Enuerate GigE and USB devicestry {stDeviceList = MV_CC_EnumDevices(MV_GIGE_DEVICE | MV_USB_DEVICE);if (0 >= stDeviceList.size()) {System.out.println("No devices found!");break;}int i = 0;for (MV_CC_DEVICE_INFO stDeviceInfo : stDeviceList) {System.out.println("[camera " + (i++) + "]");printDeviceInfo(stDeviceInfo);}} catch (CameraControlException e) {System.err.println("Enumrate devices failed!" + e.toString());e.printStackTrace();break;}// choose cameracamIndex = chooseCamera(stDeviceList,camIndex);if (camIndex == -1) {break;}// Create handletry {hCamera = MvCameraControl.MV_CC_CreateHandle(stDeviceList.get(camIndex));} catch (CameraControlException e) {System.err.println("Create handle failed!" + e.toString());e.printStackTrace();hCamera = null;break;}// Open devicenRet = MvCameraControl.MV_CC_OpenDevice(hCamera);if (MV_OK != nRet) {System.err.printf("Connect to camera failed, errcode: [%#x]\n", nRet);break;}needConnectDevice = false;}/*测试线路选择器*/// Make sure that trigger mode is offnRet = MvCameraControl.MV_CC_SetEnumValueByString(hCamera, "TriggerMode", "On");if (MV_OK != nRet) {System.err.printf("SetTriggerMode failed, errcode: [%#x]\n", nRet);break;}// Get payload sizeMVCC_INTVALUE stParam = new MVCC_INTVALUE();nRet = MvCameraControl.MV_CC_GetIntValue(hCamera, "PayloadSize", stParam);if (MV_OK != nRet) {System.err.printf("Get PayloadSize fail, errcode: [%#x]\n", nRet);break;}// Start grabbingnRet = MvCameraControl.MV_CC_StartGrabbing(hCamera);if (MV_OK != nRet) {System.err.printf("Start Grabbing fail, errcode: [%#x]\n", nRet);break;}// Get one frameMV_FRAME_OUT_INFO stImageInfo = new MV_FRAME_OUT_INFO();byte[] pData = new byte[(int) stParam.curValue];nRet = MvCameraControl.MV_CC_GetOneFrameTimeout(hCamera, pData, stImageInfo, 1000);if (MV_OK != nRet) {System.err.printf("GetOneFrameTimeout fail, errcode:[%#x]\n", nRet);break;}// System.out.println("GetOneFrame: ");printFrameInfo(stImageInfo);int imageLen = stImageInfo.width * stImageInfo.height * 3;    // Every RGB pixel takes 3 bytesbyte[] imageBuffer = new byte[imageLen];// Call MV_CC_SaveImage to save image as JPEGMV_SAVE_IMAGE_PARAM stSaveParam = new MV_SAVE_IMAGE_PARAM();stSaveParam.width = stImageInfo.width;                                  // image widthstSaveParam.height = stImageInfo.height;                                // image heightstSaveParam.data = pData;                                               // image datastSaveParam.dataLen = stImageInfo.frameLen;                             // image data lengthstSaveParam.pixelType = stImageInfo.pixelType;                          // image pixel formatstSaveParam.imageBuffer = imageBuffer;                                  // output image bufferstSaveParam.imageType = MV_SAVE_IAMGE_TYPE.MV_Image_Jpeg;               // output image pixel formatstSaveParam.methodValue = 0;                                            // Interpolation method that converts Bayer format to RGB24.  0-Neareast 1-double linear 2-HamiltonstSaveParam.jpgQuality = 60;                                            // JPG endoding quality(50-99]nRet = MvCameraControl.MV_CC_SaveImage(hCamera, stSaveParam);if (MV_OK != nRet) {//System.err.printf("SaveImage fail, errcode: [%#x]\n", nRet);// System.out.println(sfTime.format(new Date())+" "+ nRet + " No Image Need Save...");// break;//continue;} else {// 保存照片的方法 Save buffer content to fileString savePathFull = savePath+ sfSave.format(new Date())+"/"+"camera"+camIndex+"/";saveDataToFile(imageBuffer, stSaveParam.imageLen, "SaveImage-" + sfSecond.format(new Date())+ ".jpeg",savePathFull);// 有新图片保存时,删除X天前保存图片的文件夹Calendar calendar = Calendar.getInstance();calendar.setTime(new Date());// X天前的日期calendar.add(Calendar.DATE,(-deleteDay));String deleteFile = savePath+sfSave.format(calendar.getTime())+"/";FileUtil.deleteAllFile(deleteFile);}// Stop grabbingnRet = MvCameraControl.MV_CC_StopGrabbing(hCamera);if (MV_OK != nRet) {System.err.printf("StopGrabbing fail, errcode: [%#x]\n", nRet);break;}//            try {//                Thread.sleep(1000);//            } catch (InterruptedException e) {//                e.printStackTrace();//            }} while (true);if (null != hCamera) {// Destroy handlenRet = MvCameraControl.MV_CC_DestroyHandle(hCamera);if (MV_OK != nRet) {System.err.printf("DestroyHandle failed, errcode: [%#x]\n", nRet);}}}/*** 根据年月日计算图片的路径* @return*/private static String imagePathFun(){SimpleDateFormat sfDate = new SimpleDateFormat("yyyy-M-d");return "/home/hello/MVS/catch_image/"+sfDate.format(new Date())+"/";}
}

运行结果

在这里插入图片描述
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/754696.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

供应链投毒预警 | 开源供应链投毒202402月报发布啦

概述 悬镜供应链安全情报中心通过持续监测全网主流开源软件仓库&#xff0c;结合程序动静态分析方式对潜在风险的开源组件包进行动态跟踪和捕获&#xff0c;发现大量的开源组件恶意包投毒攻击事件。在2024年2月份&#xff0c;悬镜供应链安全情报中心在NPM官方仓库&#xff08;…

快速搭建一个一元二次方程flask应用

新建flask_service目录、templates子目录 flask_service —— app.py —— templates —— —— index.html app.py from flask import Flask, request, jsonify, render_template import random import matplotlib.pyplot as plt from io import BytesIO import base64app F…

jenkins Pipeline接入mysql

背景&#xff1a; jenkin pipeline进化过程如下&#xff1a; Jenkins Pipeline 脚本优化实践&#xff1a;从繁琐到简洁 >>>>> Jenkins Pipeline脚本优化&#xff1a;为Kubernetes应用部署增加状态检测>>>>>> 使用Jenkins和单个模板部署多个K…

BootScrap详细教程

文章目录 前言一、BootScrap入门二、导航三、栅格系统四、container五、面板六、媒体对象七、分页八、图标九、实现动态效果 前言 BootScrap是别人帮我们写好的CSS样式。如果想要使用BootScrap&#xff0c;需要先下载下来&#xff0c;在页面上引入&#xff0c;编写HTML需要按照…

Android 开发环境搭建(Android Studio 安装图文详细教程)

Android Studio 下载 https://developer.android.google.cn/studio?hlzh-cn Android Studio 安装 检查电脑是否启用虚拟化 如果没有开启虚拟化&#xff0c;则需要进入电脑的 BIOS 中开启 直接 next选择安装的组件&#xff0c;Android Studio 和 Android 虚拟设备&#xff…

(学习日记)2024.03.18:UCOSIII第二十节:移植到STM32

写在前面&#xff1a; 由于时间的不足与学习的碎片化&#xff0c;写博客变得有些奢侈。 但是对于记录学习&#xff08;忘了以后能快速复习&#xff09;的渴望一天天变得强烈。 既然如此 不如以天为单位&#xff0c;以时间为顺序&#xff0c;仅仅将博客当做一个知识学习的目录&a…

注册个人小程序

访问地址 https://mp.weixin.qq.com/ 立即注册 选择小程序 注册 填写信息 登录邮箱 访问邮箱的链接激活账号 选择个人&#xff0c;填写信息 注册完成&#xff0c;即可登录进入填写信息

使用jenkins-pipeline进行利用项目文件自动化部署到k8s上

Discard old builds:丢弃旧的构建,目的是管理存储空间、提升性能以及保持环境整洁 Do not allow concurrent builds: 禁止并发构建是指同一时间内只允许一个构建任务执行,避免多个构建同时运行可能带来的问题 Do not allow the pipeline to resume if the controller resta…

深度学习实战模拟——softmax回归(图像识别并分类)

目录 1、数据集&#xff1a; 2、完整代码 1、数据集&#xff1a; 1.1 Fashion-MNIST是一个服装分类数据集&#xff0c;由10个类别的图像组成&#xff0c;分别为t-shirt&#xff08;T恤&#xff09;、trouser&#xff08;裤子&#xff09;、pullover&#xff08;套衫&#xf…

蓝桥杯-24点-搜索

题目 思路 --暴力递归全组合的方法。只有4个数&#xff0c;4种计算方式&#xff0c;共有4 * 3 * 2 * 1 * 4种不同的情况&#xff0c;可以写递归来实现。 --每次计算都是两个数之间的运算&#xff0c;因此4个数需要3次计算&#xff0c;第一次计算前有4个数&#xff0c;第二次有…

面向对象【interface接口、抽象类与抽象方法】

文章目录 interface接口定义接口接口的格式与举例静态方法私有方法接口的多继承接口的默认方法冲突解决接口与抽象类之间的对比 抽象类与抽象方法抽象类抽象类的定义抽象方法使用抽象类 参考链接 interface接口 接口是一种抽象的数据类型&#xff0c;它定义了一组方法&#xff…

c语言基础~函数详解

前言 今天我们来学习一波函数的概念,帮助各位理解函数,本次博客取自一些书籍以及各大网站的讲解,把它整合在一起并且详细讲解 1函数的理解 我们得知道什么是函数&#xff0c;函数的作用是什么,好不会表述没关系&#xff0c;我们翻书 c primer plus 是这么说的"函数是指…

科技云报道:第五次工业革命,中国AI企业如何打造新质生产力?

科技云报道原创。 人类历史的叙述与技术进步的影响深深交织在一起。 迄今为止&#xff0c;每一次工业革命都彻底改变了我们社会的轮廓&#xff0c;引入了机械化、大规模生产和数字化&#xff0c;并重新定义了人类生存的规范。 自2022年11月30日OpenAI发布ChatGPT以来&#x…

C++Qt学习——QFile、QPainter、QChart

目录 1、QFile&#xff08;文本读写&#xff09;——概念 1.1、拖入三个控件&#xff0c;对pushButton进行水平布局&#xff0c;之后整体做垂直布局 1.2、按住控件&#xff0c;转到槽&#xff0c;写函数 1.3、打开文件控件 A、首先引入以下两个头文件 B、设置点击打开文件控…

C++进阶之路---手撕“红黑树”

顾得泉&#xff1a;个人主页 个人专栏&#xff1a;《Linux操作系统》 《C从入门到精通》 《LeedCode刷题》 键盘敲烂&#xff0c;年薪百万&#xff01; 一、红黑树的概念与性质 1.概念 红黑树&#xff0c;是一种二叉搜索树&#xff0c;但在每个结点上增加一个存储位表示结点…

多模态数据融合简介#翻译

翻译自—— 感谢外国友人分享&#xff0c;鄙人在此翻译分享给大家INTRODUCTION TO DATA FUSION. multi-modality | by Haylat T | Haileleol Tibebu | Medium 多模态梳理_多模态图像和多模态方法的区别-CSDN博客 #这个网u也写得不错&#xff01; 多模态 神经网络是最著名的机…

idea远程试调jar、远程试调war

idea远程试调jar、远程试调war 目的&#xff1a;测试运行时与ide开发时是否一致。 配置jar Maven中添加 <packaging>jar</packaging>将其打包为jar。 设置运行入口main 编译jar 看到jar输出 配置试调 添加jar运行 远程试调 先在源码中打好断点试调 debug运行…

React的基本使用

安装VSCode插件 ES7 Reactopen in browser React基本使用 基本使用步骤 引入两个JS文件&#xff08; 注意引入顺序 &#xff09; <!-- react库, 提供React对象 --> //本地 <script src"../js/react.development.js"></script> //线上 //<scr…

Python大数据实践:selenium爬取京东评论数据

准备工作 selenium安装 Selenium是广泛使用的模拟浏览器运行的库&#xff0c;用于Web应用程序测试。 Selenium测试直接运行在浏览器中&#xff0c;就像真正的用户在操作一样&#xff0c;并且支持大多数现代 Web 浏览器。 #终端pip安装 pip install selenium #清华镜像安装 p…

【Ubuntu】Ubuntu的安装和配置

下载ubuntu镜像 https://releases.ubuntu.com/22.04.4/ubuntu-22.04.4-desktop-amd64.iso 一、Ubuntu安装 1.新建虚拟机 1.1按照它的提示创建用户&#xff1b;后面一直下一步就好 2.启动Ubuntu虚拟机 2.1设置为中文键盘 2.2默认即可&#xff1b;若是有低需求也可以选择最小…