网络摄像头

This commit is contained in:
lixiao 2025-09-11 10:44:25 +08:00
parent 52953bda36
commit a5debed8f9
5 changed files with 116 additions and 80 deletions

View File

@ -0,0 +1,95 @@
import http from '@ohos.net.http';
import buffer from '@ohos.buffer';
import image from '@ohos.multimedia.image';
const TAG = 'CameraService';
export async function ObtainNetworkCameraImages(ip: string,userName: string, pwd: string): Promise<string | null> {
// const url = "http://192.168.1.125/snapshot.cgi?stream=1&username=admin&password=123456";
const url = `http://${ip}/snapshot.cgi?stream=1&username=${userName}&password=${pwd}`;
let httpRequest = http.createHttp();
console.log(TAG, url)
try {
console.info(TAG, 'Starting image request...');
const response = await httpRequest.request(url, {
method: http.RequestMethod.GET,
connectTimeout: 10000,
readTimeout: 10000,
expectDataType: http.HttpDataType.ARRAY_BUFFER,
});
if (response.responseCode === 200) {
let arrayBuffer = response.result as ArrayBuffer;
// 裁剪左半部分
const croppedBase64 = await cropLeftHalf(arrayBuffer);
return croppedBase64;
} else {
console.error(TAG, `HTTP Error: ${response.responseCode}`);
return null;
}
} catch (error) {
console.error(TAG, 'An error occurred while fetching the image.', JSON.stringify(error));
return null;
} finally {
httpRequest.destroy();
}
}
async function cropLeftHalf(arrayBuffer: ArrayBuffer): Promise<string> {
let imageSource: image.ImageSource | null = null;
let pixelMap: image.PixelMap | null = null;
try {
// 1. 创建ImageSource
imageSource = image.createImageSource(arrayBuffer);
// 2. 获取图片信息
const imageInfo = await imageSource.getImageInfo();
console.info(TAG, `Original image size: ${imageInfo.size.width}x${imageInfo.size.height}`);
// 3. 计算并定义左半部分的裁剪区域
const leftHalfWidth = Math.floor(imageInfo.size.width / 2);
const cropRegion: image.Region = {
size: {
width: leftHalfWidth,
height: imageInfo.size.height
},
x: leftHalfWidth,
y: 0
};
// 创建解码选项,并将裁剪区域放入其中
const decodingOptions: image.DecodingOptions = {
desiredRegion: cropRegion
};
// 4. 创建像素映射并进行裁剪
pixelMap = await imageSource.createPixelMap(decodingOptions);
// 5. 将裁剪后的PixelMap转换为ArrayBuffer
const imagePacker = image.createImagePacker();
const packedData = await imagePacker.packing(pixelMap, {
format: "image/jpeg",
quality: 90
});
// 6. 转换为Base64
const buf = buffer.from(packedData);
const base64 = buf.toString('base64');
const result = `${base64}`;
console.info(TAG, `Left half cropped successfully. Size: ${leftHalfWidth}x${imageInfo.size.height}`);
return result;
} catch (error) {
console.error(TAG, 'Image cropping failed:', JSON.stringify(error));
return "";
} finally {
// 7. 在 finally 块中安全地释放资源
imageSource?.release();
pixelMap?.release();
}
}

View File

@ -1,17 +1,13 @@
import mediaLibrary from '@ohos.multimedia.mediaLibrary'
import onvifclient from '@ohos.onvifclient';
import fs from '@ohos.file.fs'
// @ts-ignore
import photoAccessHelper from '@ohos.file.photoAccessHelper'
import dataSharePredicates from '@ohos.data.dataSharePredicates'
import { dateFormat, getCurrentTime, isSevenDaysAgo } from '../utils/tools'
// import rtsp_server from '@ohos.rtsprecord';
import record from '@ohos.rtsprecord';
import { FileHelper } from './FileHelper';
import FileUtil from '../utils/File';
import { GlobalConfig } from '../../config';
import promptAction from '@ohos.promptAction';
import { ObtainNetworkCameraImages } from './networkCamera';
const rtsp_server = record.createServer();
//开始录屏
@ -32,8 +28,6 @@ const FILE_ASSET_FETCH_COLUMNS = [photoAccessHelper.PhotoKeys.URI,
photoAccessHelper.PhotoKeys.DATE_TRASHED,
photoAccessHelper.PhotoKeys.HIDDEN];
// const rtsp_server = record.createServer();
export async function startRecordVideo(param, td, context, dir, path?, index?) {
return new Promise(async (reslove, reject) => {
// const fileUtil = new FileUtil(globalThis.context)
@ -212,74 +206,13 @@ export async function delPic(day, type) {
}
export async function takePhoto(param, context, dir, flag = 1, callback?) {
var video_uri = `rtsp://${param.userName}:${param.pwd}@${param.ip}:${param.port}/h264/ch${param.pztd}/main/av_stream`;
// var video_uri = `rtsp://admin:openharmony1@192.168.1.66:554/Streaming/Channels/3`;
const num = Math.floor(Math.random() * 10000)
const fileName = `picture_record${num}.jpg`
console.log('baoyihubaoyihu', video_uri, flag)
console.log(`baoyihu Rtsprecord baohaowen getVideoSnapshot fileName` + fileName);
// @ts-ignore
// var snapResult = rtsp_server.getVideoSnapshot(context, video_uri, '', dir);
if (flag == 0) {
// return new
return new Promise<takePhotoParam>(async (resolve, reject) => {
rtsp_server.detectVideoSnapshotSize(video_uri, fileName, false, (err, snapResult) => {
console.log("baohaowen_detectLoop round end size1:" + snapResult.fileSize, snapResult.dataString);
callback && callback({
fileSize: snapResult.fileSize,
errorCode: snapResult.errorCode,
base64: snapResult.dataString
})
resolve({ fileSize: snapResult.fileSize, errorCode: snapResult.errorCode, base64: snapResult.dataString })
});
})
} else {
return new Promise<takePhotoParam>(async (resolve, reject) => {
// const time = await getCurrentTime()
// const date = time.split(' ')[0]
// let dirName = dir ? dir : date
rtsp_server.detectVideoSnapshotSize(video_uri, fileName, true, (err, snapResult) => {
if (snapResult.result && snapResult.errorCode == 0) {
console.log("baohaowen_detectLoop round end size1:" + snapResult.fileSize, snapResult.dataString);
callback && callback({
fileSize: snapResult.fileSize,
errorCode: snapResult.errorCode,
base64: snapResult.dataString
})
resolve({ fileSize: snapResult.fileSize, errorCode: snapResult.errorCode, base64: snapResult.dataString })
} else {
promptAction.showToast({
message: `拍照失败`,
duration: 3000
});
reject(false)
}
});
// rtsp_server.getVideoSnapshot(context, video_uri, fileName, dirName, true, async (err, snapResult) => {
// if (snapResult.result && snapResult.errorCode == 0) {
// resolve({
// base64: snapResult.dataString,
// name: snapResult.fileName,
// fileSize: snapResult.fileSize,
// errorCode: snapResult.errorCode,
// path: snapResult.filePath
// })
// } else {
// promptAction.showToast({
// message: `拍照失败`,
// duration: 3000
// });
// reject(false)
// // reject()
// }
//
// });
})
let base64 = await ObtainNetworkCameraImages(param.ip, param.userName, param.pwd)
let result : takePhotoParam = {
name: "",
base64,
path: "",
}
return result
}
export async function deleteAllPicturesFn() {

View File

@ -16,7 +16,7 @@ export const GlobalConfig={
//杭州
hz:{
km2:['2022.03.14.01','2022.03.17.1'],
km3:[],
km3:['2024.08.21.01','2024.08.24.1'],
},
//黑龙江
hlg:{

View File

@ -52,8 +52,8 @@ export default class EntryAbility extends UIAbility {
globalThis.deviceNo = '';
globalThis.hasAuth = false
globalThis.version = GlobalConfig.version.jn.km3[0];
globalThis.judgeVersion = GlobalConfig.version.jn.km3[1];
globalThis.version = GlobalConfig.version.hz.km3[0];
globalThis.judgeVersion = GlobalConfig.version.hz.km3[1];
globalThis.tcpSendNum = 0
globalThis.videoVersion = '1.0'
globalThis.tcpStep=0

View File

@ -67,6 +67,8 @@ function ifNeedRetry(code: number | string): boolean {
}
export default class Judge {
private endPhoto: string = ""
// 过程照片拍照
getPhoto = async (empty?: boolean) => {
const singlePlay = globalThis.singlePlay
@ -536,9 +538,12 @@ export default class Judge {
private isJudgeDisConnect: boolean;
// 项目开始接口同步
beginProject = async (ksxm) => {
const { judgeUI, fileLog, getSbbm, xmxh, filePath, getPhoto } = this;
if (ksxm == '11') {
this.endPhoto = await getPhoto()
}
const carInfo = globalThis.carInfo;
const { examSubject, plateNo } = carInfo;
const { judgeUI, fileLog, getSbbm, xmxh, filePath } = this;
const { lsh, idCard, serialNumber, projectsObj, ksdd, kslx, xldm } = judgeUI
const time = await getCurrentTime();
const project = projectsObj[ksxm]
@ -1314,7 +1319,11 @@ export default class Judge {
// await uploadDisConnectData();
try {
const time = await getCurrentTime();
const photoBase64 = await getPhoto();
let photoBase64 = this.endPhoto
if (!photoBase64) {
photoBase64 = await getPhoto();
}
// const photoBase64 = await getPhoto();
const { d1, d2, d3, d4, d5 } = ksjs
const data = {
xtlb: '17',
@ -1330,7 +1339,6 @@ export default class Judge {
jssj: time,
kscj: (totalScore * 1) > 0 ? totalScore : 0,
kslc: Math.ceil(((ksjs?.qjjl + ksjs?.dcjl) || 0) / 100),
// 1,22;2,560;3,128;4,0;5,0;
dwlc: [d1, d2, d3, d4, d5].map((d, index) => `${index + 1},${Math.floor(d / 100)}`).join(';'),
}
}