Skip to main content

nativeImage

使用 PNG 或 JPG 文件创建托盘、任务栏和应用图标。

进程:主进程渲染器

🌐 Process: Main, Renderer

info

如果你想从启用上下文隔离的渲染进程调用此 API, 请将 API 调用放在你的 preload 脚本中,并 使用 contextBridge API 暴露 它。

nativeImage 模块提供了一个用于操作系统图片的统一接口。如果你想提供同一图标的多个缩放版本或者利用 macOS 模板图片 的功能,这会很方便。

🌐 The nativeImage module provides a unified interface for manipulating system images. These can be handy if you want to provide multiple scaled versions of the same icon or take advantage of macOS template images.

接受图片文件的 Electron API 可以使用文件路径或 NativeImage 实例。当传入 null 时,将使用一个空白且透明的图片。

🌐 Electron APIs that take image files accept either file paths or NativeImage instances. An empty and transparent image will be used when null is passed.

例如,在创建 Tray 或设置 BrowserWindow 的图标时,你可以传入图片文件路径作为字符串:

🌐 For example, when creating a Tray or setting a BrowserWindow's icon, you can either pass an image file path as a string:

Main Process
const { BrowserWindow, Tray } = require('electron')

const tray = new Tray('/Users/somebody/images/icon.png')
const win = new BrowserWindow({ icon: '/Users/somebody/images/window.png' })

或者从同一个文件生成一个 NativeImage 实例:

🌐 or generate a NativeImage instance from the same file:

Main Process
const { BrowserWindow, nativeImage, Tray } = require('electron')

const trayIcon = nativeImage.createFromPath('/Users/somebody/images/icon.png')
const appIcon = nativeImage.createFromPath('/Users/somebody/images/window.png')
const tray = new Tray(trayIcon)
const win = new BrowserWindow({ icon: appIcon })

支持的格式

🌐 Supported Formats

目前,PNGJPEG 图片格式在所有平台上都受支持。PNG 被推荐使用,因为它支持透明度和无损压缩。

🌐 Currently, PNG and JPEG image formats are supported across all platforms. PNG is recommended because of its support for transparency and lossless compression.

在 Windows 上,你也可以从文件路径加载 ICO 图标。为了获得最佳视觉效果,我们建议至少包含以下尺寸:

🌐 On Windows, you can also load ICO icons from file paths. For best visual quality, we recommend including at least the following sizes:

  • 小图标
    • 16x16(100% DPI 比例)
    • 20x20(125% DPI 比例)
    • 24x24(150% DPI 比例)
    • 32x32(200% DPI 比例)
  • 大图标
    • 32x32(100% DPI 比例)
    • 40x40(125% DPI 比例)
    • 48x48(150% DPI 比例)
    • 64x64(200% DPI 比例)
    • 256x256

请查看 Windows 应用图标构建 参考中的 图标缩放 部分。

🌐 Check the Icon Scaling section in the Windows App Icon Construction reference.

note

当前不支持 EXIF 元数据,在图片编码和解码进程中不会被考虑。

🌐 EXIF metadata is currently not supported and will not be taken into account during image encoding and decoding.

高分辨率图片

🌐 High Resolution Image

在支持高像素密度显示屏的平台上(例如 Apple Retina),你可以在图片的基础文件名后添加 @2x 来标记它为 2 倍分辨率的高清图片。

🌐 On platforms that support high pixel density displays (such as Apple Retina), you can append @2x after image's base filename to mark it as a 2x scale high resolution image.

例如,如果 icon.png 是具有标准分辨率的普通图片,那么 icon@2x.png 将被视为具有双倍每英寸点数(DPI)密度的高分辨率图片。

🌐 For example, if icon.png is a normal image that has standard resolution, then icon@2x.png will be treated as a high resolution image that has double Dots per Inch (DPI) density.

如果你想同时支持不同DPI密度的显示屏,可以将不同尺寸的图片放在同一个文件夹中,并在Electron中使用不带DPI后缀的文件名。例如:

🌐 If you want to support displays with different DPI densities at the same time, you can put images with different sizes in the same folder and use the filename without DPI suffixes within Electron. For example:

images/
├── icon.png
├── icon@2x.png
└── icon@3x.png
Main Process
const { Tray } = require('electron')

const appTray = new Tray('/Users/somebody/images/icon.png')

还支持以下 DPI 后缀:

🌐 The following suffixes for DPI are also supported:

  • @1x
  • @1.25x
  • @1.33x
  • @1.4x
  • @1.5x
  • @1.8x
  • @2x
  • @2.5x
  • @3x
  • @4x
  • @5x

模板图片_macOS_

🌐 Template Image macOS

在 macOS 上,模板图片 由黑色和一个 alpha 通道组成。模板图片并不是作为独立图片使用的,通常与其他内容混合以创建所需的最终效果。

🌐 On macOS, template images consist of black and an alpha channel. Template images are not intended to be used as standalone images and are usually mixed with other content to create the desired final appearance.

最常见的情况是为菜单栏(托盘)图标使用模板图片,这样它可以适应浅色和深色的菜单栏。

🌐 The most common case is to use template images for a menu bar (Tray) icon, so it can adapt to both light and dark menu bars.

要将图片标记为模板图片,其基本文件名应以 Template 结尾(例如 xxxTemplate.png)。你还可以在不同的 DPI 密度下指定模板图片(例如 xxxTemplate@2x.png)。

🌐 To mark an image as a template image, its base filename should end with the word Template (e.g. xxxTemplate.png). You can also specify template images at different DPI densities (e.g. xxxTemplate@2x.png).

方法

🌐 Methods

nativeImage 模块具有以下方法,所有方法都返回 NativeImage 类的实例:

🌐 The nativeImage module has the following methods, all of which return an instance of the NativeImage class:

nativeImage.createEmpty()

返回 NativeImage

🌐 Returns NativeImage

创建一个空的 NativeImage 实例。

🌐 Creates an empty NativeImage instance.

nativeImage.createThumbnailFromPath(path, size) macOS Windows

  • path 字符串 - 我们打算用它来生成缩略图的文件路径。
  • size 尺寸 - 缩略图的期望宽度和高度(正数)。

返回 Promise<NativeImage> - 已完成,带有文件的缩略图预览图片,该图片是一个 NativeImage

🌐 Returns Promise<NativeImage> - fulfilled with the file's thumbnail preview image, which is a NativeImage.

note

Windows 实现将忽略 size.height 并根据 size.width 缩放高度。

nativeImage.createFromPath(path)

  • path 字符串 - 我们打算用它来构建图片的文件路径。

返回 NativeImage

🌐 Returns NativeImage

从位于 path 的图片文件(例如 PNG 或 JPEG)创建一个新的 NativeImage 实例。 如果 path 不存在、无法读取或不是有效的图片,则此方法返回一个空图片。

🌐 Creates a new NativeImage instance from an image file (e.g., PNG or JPEG) located at path. This method returns an empty image if the path does not exist, cannot be read, or is not a valid image.

const { nativeImage } = require('electron')

const image = nativeImage.createFromPath('/Users/somebody/images/icon.png')
console.log(image)

nativeImage.createFromBitmap(buffer, options)

  • buffer 缓冲区
  • options 对象
    • width 整数
    • height 整数
    • scaleFactor 数字(可选)- 默认为 1.0。

返回 NativeImage

🌐 Returns NativeImage

buffer 创建一个新的 NativeImage 实例,该实例包含由 toBitmap() 返回的原始位图片素数据。具体格式取决于平台。

🌐 Creates a new NativeImage instance from buffer that contains the raw bitmap pixel data returned by toBitmap(). The specific format is platform-dependent.

nativeImage.createFromBuffer(buffer[, options])

  • buffer 缓冲区
  • options 对象(可选)
    • width 整数(可选)- 位图缓冲区必需。
    • height 整数(可选)- 位图缓冲区必需。
    • scaleFactor 数字(可选)- 默认为 1.0。

返回 NativeImage

🌐 Returns NativeImage

buffer 创建一个新的 NativeImage 实例。首先尝试以 PNG 或 JPEG 格式解码。

🌐 Creates a new NativeImage instance from buffer. Tries to decode as PNG or JPEG first.

nativeImage.createFromDataURL(dataURL)

  • dataURL 字符串

返回 NativeImage

🌐 Returns NativeImage

dataUrl 创建一个新的 NativeImage 实例,dataUrl 是一个 Base64 编码的 数据 URL 字符串。

🌐 Creates a new NativeImage instance from dataUrl, a base 64 encoded Data URL string.

nativeImage.createFromNamedImage(imageName[, hslShift]) macOS

  • imageName 字符串
  • hslShift 数字数组(可选)

返回 NativeImage

🌐 Returns NativeImage

从映射到给定图片名称的 NSImage 创建一个新的 NativeImage 实例。有关可能的值列表,请参见苹果的 NSImageName 文档和 SF Symbols

🌐 Creates a new NativeImage instance from the NSImage that maps to the given image name. See Apple's NSImageName documentation and SF Symbols for a list of possible values.

hslShift 应用于图片时遵循以下规则:

🌐 The hslShift is applied to the image with the following rules:

  • hsl_shift[0](色调):图片的绝对色调值 - 0 和 1 对应色轮上的 0 和 360(红色)。
  • hsl_shift[1](饱和度):图片的饱和度调整,关键值如下:0 = 去除所有颜色;0.5 = 保持不变;1 = 完全饱和图片。
  • hsl_shift[2](亮度):图片的亮度调整,其关键数值如下:0 = 去除所有亮度(所有像素变黑);0.5 = 保持不变;1 = 最大亮度(所有像素变白)。

这意味着 [-1, 0, 1] 会使图片完全变白,而 [-1, 1, 0] 会使图片完全变黑。

🌐 This means that [-1, 0, 1] will make the image completely white and [-1, 1, 0] will make the image completely black.

在某些情况下,NSImageName 与其字符串表示不匹配;一个例子是 NSFolderImageName,其字符串表示实际上是 NSFolder。因此,在传入图片之前,你需要确定其正确的字符串表示。这可以通过以下方法完成:

🌐 In some cases, the NSImageName doesn't match its string representation; one example of this is NSFolderImageName, whose string representation would actually be NSFolder. Therefore, you'll need to determine the correct string representation for your image before passing it in. This can be done with the following:

echo -e '#import <Cocoa/Cocoa.h>\nint main() { NSLog(@"%@", SYSTEM_IMAGE_NAME); }' | clang -otest -x objective-c -framework Cocoa - && ./test

其中 SYSTEM_IMAGE_NAME 应替换为 此列表 中的任意值。

🌐 where SYSTEM_IMAGE_NAME should be replaced with any value from this list.

对于 SF Symbols,用法如下:

🌐 For SF Symbols, usage looks as follows:

const image = nativeImage.createFromNamedImage('square.and.pencil')

其中 'square.and.pencil' 是来自 SF Symbols 应用 的符号名称。

🌐 where 'square.and.pencil' is the symbol name from the SF Symbols app.

类:NativeImage

🌐 Class: NativeImage

原生封装图片,例如托盘、停靠栏和应用图标。

进程: 主进程, Renderer
此类未从 'electron' 模块导出。它仅作为 Electron API 中其他方法的返回值使用。

实例方法

🌐 Instance Methods

NativeImage 类的实例可以使用以下方法:

🌐 The following methods are available on instances of the NativeImage class:

image.toPNG([options])

  • options 对象(可选)
    • scaleFactor 数字(可选)- 默认为 1.0。

返回 Buffer - 一个包含图片 PNG 编码数据的 缓冲区

🌐 Returns Buffer - A Buffer that contains the image's PNG encoded data.

image.toJPEG(quality)

  • quality 整数 - 范围 0 到 100。

返回 Buffer - 一个包含图片 JPEG 编码数据的 缓冲区

🌐 Returns Buffer - A Buffer that contains the image's JPEG encoded data.

image.toBitmap([options])

  • options 对象(可选)
    • scaleFactor 数字(可选)- 默认为 1.0。

返回 Buffer - 一个包含图片原始位图片素数据副本的 缓冲区

🌐 Returns Buffer - A Buffer that contains a copy of the image's raw bitmap pixel data.

image.toDataURL([options])

History
  • options 对象(可选)
    • scaleFactor 数字(可选)- 默认为 1.0。

返回 string - 图片的 数据 URL

🌐 Returns string - The Data URL of the image.

image.getBitmap([options]) 已弃用

🌐 image.getBitmap([options]) Deprecated

  • options 对象(可选)
    • scaleFactor 数字(可选)- 默认为 1.0。

image.toBitmap() 的遗留别名。

🌐 Legacy alias for image.toBitmap().

image.getNativeHandle() macOS

返回 Buffer - 一个 缓冲区,用于存储指向图片底层原生句柄的 C 指针。在 macOS 上,将返回指向 NSImage 实例的指针。

🌐 Returns Buffer - A Buffer that stores C pointer to underlying native handle of the image. On macOS, a pointer to NSImage instance is returned.

请注意,返回的指针是指向底层原生图片的弱指针,而不是一个副本,因此你必须确保相关的 nativeImage 实例被保留。

🌐 Notice that the returned pointer is a weak pointer to the underlying native image instead of a copy, so you must ensure that the associated nativeImage instance is kept around.

image.isEmpty()

返回 boolean - 图片是否为空。

🌐 Returns boolean - Whether the image is empty.

image.getSize([scaleFactor])

  • scaleFactor 数字(可选)- 默认为 1.0。

返回 Size

🌐 Returns Size.

如果传入 scaleFactor,这将返回与传入值最接近的图片表示对应的大小。

🌐 If scaleFactor is passed, this will return the size corresponding to the image representation most closely matching the passed value.

image.setTemplateImage(option)

  • option 布尔值

将图片标记为 macOS 模板图片

🌐 Marks the image as a macOS template image.

image.isTemplateImage()

返回 boolean - 图片是否为 macOS 模板图片

🌐 Returns boolean - Whether the image is a macOS template image.

image.crop(rect)

  • rect 矩形 - 要裁剪的图片区域。

返回 NativeImage - 裁剪后的图片。

🌐 Returns NativeImage - The cropped image.

image.resize(options)

  • options 对象
    • width 整数(可选)- 默认为图片的宽度。
    • height 整数(可选)- 默认为图片的高度。
    • quality 字符串(可选)- 调整大小图片的期望质量。可能的值包括 goodbetterbest。默认值为 best。这些值表示期望的质量/速度权衡。它们会被转换为依赖于底层平台(CPU、GPU)能力的特定算法方法。在给定平台上,三种方法有可能映射到同一个算法。

返回 NativeImage - 已调整大小的图片。

🌐 Returns NativeImage - The resized image.

如果只指定了 heightwidth,则在调整图片大小时会保持当前的宽高比。

🌐 If only the height or the width are specified then the current aspect ratio will be preserved in the resized image.

image.getAspectRatio([scaleFactor])

  • scaleFactor 数字(可选)- 默认为 1.0。

返回 Number - 图片的纵横比(宽度除以高度)。

🌐 Returns Number - The image's aspect ratio (width divided by height).

如果传入 scaleFactor,这将返回与最接近传入值的图片表示对应的纵横比。

🌐 If scaleFactor is passed, this will return the aspect ratio corresponding to the image representation most closely matching the passed value.

image.getScaleFactors()

返回 Number[] - 对应给定 NativeImage 的所有表示的比例因子数组。

🌐 Returns Number[] - An array of all scale factors corresponding to representations for a given NativeImage.

image.addRepresentation(options)

  • options 对象
    • scaleFactor 数字(可选)- 用于添加图片表示的缩放因子。
    • width 整数(可选)- 默认为 0。如果指定了 buffer 作为位图缓冲区,则必填。
    • height 整数(可选)- 默认为 0。如果指定了 buffer 作为位图缓冲区,则必填。
    • buffer 缓冲区(可选)- 包含原始图片数据的缓冲区。
    • dataURL 字符串(可选)- 包含 base64 编码的 PNG 或 JPEG 图片的数据 URL。

为特定的缩放因子添加图片表示。这可以用于以编程方式向图片添加不同的缩放因子表示。此操作也可以在空图片上调用。

🌐 Add an image representation for a specific scale factor. This can be used to programmatically add different scale factor representations to an image. This can be called on empty images.

实例属性

🌐 Instance Properties

nativeImage.isMacTemplateImage macOS

一个 boolean 属性,用于确定图片是否被视为 模板图片

🌐 A boolean property that determines whether the image is considered a template image.

请注意,此属性仅对 macOS 有效。

🌐 Please note that this property only has an effect on macOS.