You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Electron使用desktopCapturer截图如何获取大尺寸thumbnail图像

问题原因

你拿到的截图尺寸过小是desktopCapturer的默认配置导致的:getSources方法默认生成的缩略图尺寸为150×150px,大尺寸截图不需要从其他位置获取,直接通过调用参数自定义配置即可生成。

解决方法

调用desktopCapturer.getSources时传入thumbnailSize参数,指定你需要的截图宽高即可。如果要获取和当前屏幕完全匹配的全屏截图,可配合Electron的screen模块读取显示器实际分辨率,无需手动写死数值。

基础版代码示例

import { desktopCapturer, screen } from 'electron'

takeScreenshot() {
  // 获取主显示器的逻辑分辨率
  const primaryDisplay = screen.getPrimaryDisplay()
  const { width, height } = primaryDisplay.size

  desktopCapturer.getSources({ 
    types: ['screen'],
    // 自定义缩略图尺寸为屏幕实际分辨率
    thumbnailSize: { width, height }
  })
  .then( (sources: { thumbnail: { toDataURL: () => any; }; }[]) => {
    // 此时拿到的就是全尺寸截图
    const theimage = sources[0].thumbnail.toDataURL()
  })
}

高DPI屏幕适配

如果是2K/4K等高缩放屏幕,截图可能出现模糊,可乘以显示器的缩放系数获取和物理像素匹配的高清截图:

// 仅需要修改尺寸计算逻辑即可
const primaryDisplay = screen.getPrimaryDisplay()
const { width, height } = primaryDisplay.size
const scaleFactor = primaryDisplay.scaleFactor
const finalSize = {
  width: Math.floor(width * scaleFactor),
  height: Math.floor(height * scaleFactor)
}
// 把finalSize传入thumbnailSize配置即可

注意事项

如果设备接入了多个显示器,sources数组会按显示器顺序返回对应屏幕的源,不要直接固定取sources[0],可通过源的id和显示器id匹配的方式获取对应屏幕的截图,避免拿错屏幕内容。

内容的提问来源于stack exchange,提问作者deszok

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 03:48:00