在进行网页视频通话时,点击截屏按钮对视频进行截屏并保存

首先是定义视频和截屏按钮的代码;

<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;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值