随笔 - 45,  文章 - 0,  评论 - 2,  阅读 - 30144
复制代码

1
// In the renderer process. 2 3 import { desktopCapturer } from 'electron'; 4 import { screen } from '@electron/remote'; 5 6 export async function captureScreen() { 7 const url_base64 = await getCaptureBySourceThumbnail(); 8 // const url_base64 = await getCaptureByStream(await getStream()); 9 return url_base64; 10 } 11 12 // 获取屏幕尺寸 13 function getSize() { 14 // scaleFactor 缩放因子 15 const { size, scaleFactor } = screen.getPrimaryDisplay(); 16 return { 17 width: size.width * scaleFactor, 18 height: size.height * scaleFactor 19 }; 20 } 21 22 // 通过 source thumbnail 获取截图 23 async function getCaptureBySourceThumbnail() { 24 if (process.platform !== 'win32') return; 25 const sources = await desktopCapturer.getSources({ 26 types: ['window', 'screen'], 27 thumbnailSize: getSize() 28 }); 29 if (!sources || !sources.length) throw new Error('sources 为空'); 30 return sources[0].thumbnail.toDataURL(); 31 } 32 33 // 获取 web RTC 视频流 34 async function getStream() { 35 const { width, height } = getSize(); 36 37 return await navigator.mediaDevices.getUserMedia({ 38 audio: false, 39 video: { 40 mandatory: { 41 chromeMediaSource: 'desktop', 42 // chromeMediaSourceId: source.id, 43 minWidth: width, // 直接设置 width、height 会报错 44 maxWidth: width, 45 minHeight: height, 46 maxHeight: height 47 } 48 } 49 }); 50 } 51 52 // 关闭视频流 53 function closeStream(stream) { 54 const tracks = stream.getTracks() || []; 55 for (const track of tracks) { 56 track.stop(); 57 } 58 } 59 60 // 通过 web RTC 视频流获取截图(存在鼠标) 61 function getCaptureByStream(stream) { 62 const { width, height } = getSize(); 63 64 return new Promise(resolve => { 65 const _video = document.createElement('video'); 66 _video.srcObject = stream; 67 _video.onloadedmetadata = () => { 68 _video.play(); 69 70 const _canvas = document.createElement('canvas'); 71 _canvas.width = width; 72 _canvas.height = height; 73 const _context = _canvas.getContext('2d'); 74 _context.drawImage(_video, 0, 0, _canvas.width, _canvas.height); 75 const url_base64 = _canvas.toDataURL('image/png'); 76 _video.pause(); 77 closeStream(stream); 78 79 return resolve(url_base64); 80 }; 81 }); 82 }
复制代码

 

posted on   W1N9s  阅读(2181)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示