首先是定义视频和截屏按钮的代码;
<div class="layui-card-body">
<span class="layui-badge">远端视频</span>
<div id="remoteVideoZone">
<video id="remoteMediaView" controls="controls"
style="border:1px solid forestgreen;width:100%;height:200px;text-align:right">
</video>
<button id="screenshotButton">截屏</button>
</div>
</div>
紧接着为JavaScript代码用来处理按钮点击和向后端传输图片数据;
var screenshotButton = document.getElementById('screenshotButton');
screenshotButton.addEventListener('click', function() {
console.log("???")
var remoteVideo = document.getElementById('remoteMediaView');
var canvas = document.createElement('canvas');
canvas.width = remoteVideo.videoWidth;
canvas.height = remoteVideo.videoHeight;
canvas.getContext('2d').drawImage(remoteVideo, 0, 0, canvas.width, canvas.height);
var dataURL = canvas.toDataURL(); // 获取图像数据
var fileName = 'custom_filename.jpg'; // 自定义文件名
var requestData = JSON.stringify({ imageData: dataURL, fileName: fileName }); // 将图像数据和文件名打包为JSON格式
var xhr = new XMLHttpRequest();
xhr.open('POST', '/photo/screenshot');
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
xhr.send(requestData); // 发送POST请求
});
将图片数据传到后端,把数据解码处理,并将图片重新定义一个名字,存入磁盘时如果不存在文件夹会自动检测和创建,磁盘位置和文件夹名字可以自己定义;(这里的fileName为null,如果想接收前端的fileName可以从imageDataMap中提取出来,imageDataMap中包含的是图片数据和图片名)
@PostMapping("screenshot")
public String saveScreenshot(@RequestBody Map<String, String> imageDataMap, @RequestParam(required = false) String fileName) throws Exception {
String imageData = imageDataMap.get("imageData");
byte[] imageBytes = Base64.getDecoder().decode(imageData.split(",")[1]);
System.out.println("imageBytes = " + imageBytes);
if (fileName == null || fileName.trim().isEmpty()) { // 如果未指定文件名,则使用当前时间戳
fileName = "screenshot_" + System.currentTimeMillis() + ".jpg";
}
Path directoryPath = Paths.get("C:/photo");
if (!Files.isDirectory(directoryPath)) { // 如果photo目录不存在,则创建该目录
new File(directoryPath.toString()).mkdirs();
}
Path filePath = directoryPath.resolve(fileName); // 将文件保存到C:/photo目录下,并使用指定的文件名
Files.write(filePath, imageBytes);
return "已成功保存截图:" + fileName;
}