Skip to main content

nativeImage

Create tray, dock, and application icons using PNG or JPG files.使用PNG或JPG文件创建托盘、停靠和应用程序图标。

Process:进程:Main, Renderer

In Electron, for the APIs that take images, you can pass either file paths or NativeImage instances. 在Electron中,对于获取图像的API,可以传递文件路径或NativeImage实例。An empty image will be used when null is passed.传递null时将使用空图像。

For example, when creating a tray or setting a window's icon, you can pass an image file path as a string:例如,当创建托盘或设置窗口的图标时,可以将图像文件路径作为string传递:

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

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

Or read the image from the clipboard, which returns a NativeImage:或者从剪贴板中读取图像,这将返回NativeImage

const { clipboard, Tray } = require('electron')
const image = clipboard.readImage()
const appIcon = new Tray(image)
console.log(appIcon)

Supported Formats支持的格式

Currently PNG and JPEG image formats are supported. 目前支持PNGJPEG图像格式。PNG is recommended because of its support for transparency and lossless compression.建议使用PNG,因为它支持透明和无损压缩。

On Windows, you can also load ICO icons from file paths. 在Windows上,您也可以从文件路径加载ICO图标。For best visual quality, it is recommended to include at least the following sizes in the:为了获得最佳视觉质量,建议在中至少包含以下尺寸:

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

Check the Size requirements section in this article.请查看本文中的“尺寸要求”部分。

High Resolution Image高分辨率图像

On platforms that have high-DPI support such as Apple Retina displays, you can append @2x after image's base filename to mark it as a high resolution image.在支持高DPI的平台上,如Apple Retina显示器,您可以在图像的基本文件名后附加@2x,将其标记为高分辨率图像。

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 DPI density.例如,如果icon.png是具有标准分辨率的普通图像,那么icon@2x.png将被视为具有双倍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. 如果您想同时支持不同DPI密度的显示器,可以将不同大小的图像放在同一文件夹中,并使用不带DPI后缀的文件名。For example:例如:

images/
├── icon.png
├── icon@2x.png
└── icon@3x.png
const { Tray } = require('electron')
const appIcon = new Tray('/Users/somebody/images/icon.png')
console.log(appIcon)

The following suffixes for DPI are also supported:DPI还支持以下后缀:

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

Template Image模板图像

Template images consist of black and an alpha channel. 模板图像由黑色通道和alpha通道组成。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 icon, so it can adapt to both light and dark menu bars.最常见的情况是将模板图像用于菜单栏图标,因此它可以适应浅色和深色菜单栏。

Note: Template image is only supported on macOS.模板图像仅在macOS上受支持。

To mark an image as a template image, its filename should end with the word Template. 要将图像标记为模板图像,其文件名应以Template一词结尾。For example:例如:

  • xxxTemplate.png
  • xxxTemplate@2x.png

Methods方法

The nativeImage module has the following methods, all of which return an instance of the NativeImage class:nativeImage模块具有以下方法,所有这些方法都返回NativeImage类的一个实例:

nativeImage.createEmpty()

Returns返回NativeImage

Creates an empty NativeImage instance.创建一个空的NativeImage实例。

nativeImage.createThumbnailFromPath(path, maxSize) macOS Windows

  • path string - path to a file that we intend to construct a thumbnail out of.一个文件的路径,我们打算用它来构建缩略图。
  • maxSize Size - the maximum width and height (positive numbers) the thumbnail returned can be. 缩略图返回的最大宽度和高度(正数)可以是。The Windows implementation will ignore maxSize.height and scale the height according to maxSize.width.Windows实现将忽略maxSize.height并根据maxSize.width缩放高度。

Returns返回Promise<NativeImage> - fulfilled with the file's thumbnail preview image, which is a NativeImage.用文件的缩略图预览图像完成,该图像是NativeImage

nativeImage.createFromPath(path)

  • path string

Returns返回NativeImage

Creates a new NativeImage instance from a file located at path. 从位于path的文件创建一个新的NativeImage实例。This method returns an empty image if the path does not exist, cannot be read, or is not a valid image.如果path不存在、无法读取或不是有效图像,则此方法返回空图像。

const nativeImage = require('electron').nativeImage

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

nativeImage.createFromBitmap(buffer, options)

  • buffer Buffer
  • options Object
    • width Integer
    • height Integer
    • scaleFactor Double (optional) - Defaults to 1.0.默认值为1.0。

Returns返回NativeImage

Creates a new NativeImage instance from buffer that contains the raw bitmap pixel data returned by toBitmap(). 从缓冲区创建一个新的NativeImage实例,该buffer包含toBitmap()返回的原始位图像素数据。The specific format is platform-dependent.具体的格式取决于平台。

nativeImage.createFromBuffer(buffer[, options])

  • buffer Buffer
  • options Object (optional)
    • width Integer (optional) - Required for bitmap buffers.位图缓冲区需要。
    • height Integer (optional) - Required for bitmap buffers.位图缓冲区需要。
    • scaleFactor Double (optional) - Defaults to 1.0.默认值为1.0。

Returns返回NativeImage

Creates a new NativeImage instance from buffer. 根据buffer创建一个新的NativeImage实例。Tries to decode as PNG or JPEG first.尝试先解码为PNG或JPEG。

nativeImage.createFromDataURL(dataURL)

  • dataURL string

Returns返回NativeImage

Creates a new NativeImage instance from dataURL.dataURL创建一个新的NativeImage实例。

nativeImage.createFromNamedImage(imageName[, hslShift]) macOS

  • imageName string
  • hslShift number (optional)

Returns返回NativeImage

Creates a new NativeImage instance from the NSImage that maps to the given image name. 从映射到给定图像名称的NSImage创建一个新的NativeImage实例。See System Icons for a list of possible values.有关可能值的列表,请参阅系统图标

The hslShift is applied to the image with the following rules:hslShift按以下规则应用于图像:

  • hsl_shift[0] (hue)(色调): The absolute hue value for the image - 0 and 1 map to 0 and 360 on the hue color wheel (red).:图像的绝对色调值-0和1映射到色调色轮(红色)上的0和360。
  • hsl_shift[1] (saturation)(饱和度): A saturation shift for the image, with the following key values: 0 = remove all color. :图像的饱和度偏移,具有以下关键值:0=删除所有颜色。0.5 = leave unchanged. 0.5=保持不变。1 = fully saturate the image.1=使图像完全饱和。
  • hsl_shift[2] (lightness)(亮度): A lightness shift for the image, with the following key values: 0 = remove all lightness (make all pixels black). :图像的亮度偏移,使用以下关键值:0=移除所有亮度(使所有像素变黑)。0.5 = leave unchanged. 0.5=保持不变。1 = full lightness (make all pixels white).1=全亮度(使所有像素变白)。

This means that [-1, 0, 1] will make the image completely white and [-1, 1, 0] will make the image completely black.这意味着[-1, 0, 1]将使图像完全变白,[-1, 1, 0]将使图像全部变黑。

In some cases, the NSImageName doesn't match its string representation; one example of this is NSFolderImageName, whose string representation would actually be NSFolder. 在某些情况下,NSImageName与其字符串表示形式不匹配;其中一个例子是NSFolderImageName,它的字符串表示实际上是NSFolderTherefore, 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

where SYSTEM_IMAGE_NAME should be replaced with any value from this list.其中SYSTEM_IMAGE_NAME应替换为此列表中的任何值。

Class: NativeImage

Natively wrap images such as tray, dock, and application icons.以本机方式包装图像,如托盘、停靠和应用程序图标。

Process:进程:Main, Renderer
This class is not exported from the 'electron' module. 此类不是从'electron'模块导出的。It is only available as a return value of other methods in the Electron API.它只能作为Electron API中其他方法的返回值使用。

Instance Methods实例方法

The following methods are available on instances of the NativeImage class:以下方法可用于NativeImage类的实例:

image.toPNG([options])

  • options Object (optional)
    • scaleFactor Double (optional) - Defaults to 1.0.默认值为1.0。

Returns返回Buffer - A Buffer that contains the image's PNG encoded data.一个Buffer,包含图像的PNG编码数据。

image.toJPEG(quality)

  • quality Integer - Between 0 - 100.介于0到100之间。

Returns返回Buffer - A Buffer that contains the image's JPEG encoded data.包含图像的JPEG编码数据的Buffer

image.toBitmap([options])

  • options Object (optional)
    • scaleFactor Double (optional) - Defaults to 1.0.默认值为1.0。

Returns返回Buffer - A Buffer that contains a copy of the image's raw bitmap pixel data.一个Buffer,包含图像的原始位图像素数据的副本。

image.toDataURL([options])

  • options Object (optional)
    • scaleFactor Double (optional) - Defaults to 1.0.默认值为1.0。

Returns返回string - The data URL of the image.图像的数据URL。

image.getBitmap([options])

  • options Object (optional)
    • scaleFactor Double (optional) - Defaults to 1.0.默认值为1.0。

Returns返回Buffer - A Buffer that contains the image's raw bitmap pixel data.一个Buffer,包含图像的原始位图像素数据。

The difference between getBitmap() and toBitmap() is that getBitmap() does not copy the bitmap data, so you have to use the returned Buffer immediately in current event loop tick; otherwise the data might be changed or destroyed.getBitmap()toBitmap()的区别在于,getBitmap()不复制位图数据,因此您必须在当前事件循环中立即使用返回的Buffer;否则数据可能会被更改或销毁。

image.getNativeHandle() macOS

Returns返回Buffer - A Buffer that stores C pointer to underlying native handle of the image. 一个Buffer,用于存储指向映像的底层本机句柄的C游标。On macOS, a pointer to NSImage instance would be returned.在macOS上,将返回指向NSImage实例的游标。

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.请注意,返回的游标是指向底层本机映像的弱游标,而不是副本,因此必须确保保留关联的nativeImage实例。

image.isEmpty()

Returns返回boolean - Whether the image is empty.图像是否为空。

image.getSize([scaleFactor])

  • scaleFactor Double (optional) - Defaults to 1.0.默认值为1.0。

Returns Size.返回Size

If scaleFactor is passed, this will return the size corresponding to the image representation most closely matching the passed value.如果传递了scaleFactor,这将返回与传递值最匹配的图像表示对应的大小。

image.setTemplateImage(option)

  • option boolean

Marks the image as a template image.将图像标记为模板图像。

image.isTemplateImage()

Returns返回boolean - Whether the image is a template image.图像是否为模板图像。

image.crop(rect)

  • rect Rectangle - The area of the image to crop.要裁剪的图像区域。

Returns返回NativeImage - The cropped image.裁剪后的图像。

image.resize(options)

  • options Object
    • width Integer (optional) - Defaults to the image's width.默认为图像的宽度。
    • height Integer (optional) - Defaults to the image's height.默认为图像的高度。
    • quality string (optional) - The desired quality of the resize image. 调整大小图像所需的质量。Possible values are good, better, or best. 可能的值是goodbetterbestThe default is best. 默认值是bestThese values express a desired quality/speed tradeoff. 这些值表示所需的质量/速度权衡。They are translated into an algorithm-specific method that depends on the capabilities (CPU, GPU) of the underlying platform. 它们被转化为一种特定于算法的方法,该方法取决于底层平台的能力(CPU、GPU)。It is possible for all three methods to be mapped to the same algorithm on a given platform.在给定的平台上,所有三种方法都有可能映射到相同的算法。

Returns返回NativeImage - The resized image.调整大小的图像。

If only the height or the width are specified then the current aspect ratio will be preserved in the resized image.如果只指定了heightwidth,则当前纵横比将保留在调整大小的图像中。

image.getAspectRatio([scaleFactor])

  • scaleFactor Double (optional) - Defaults to 1.0.默认值为1.0。

Returns返回Float - The image's aspect ratio.图像的纵横比。

If scaleFactor is passed, this will return the aspect ratio corresponding to the image representation most closely matching the passed value.如果传递了scaleFactor,这将返回与传递值最匹配的图像表示对应的纵横比。

image.getScaleFactors()

Returns返回Float[] - An array of all scale factors corresponding to representations for a given nativeImage.与给定nativeImage的表示相对应的所有比例因子的数组。

image.addRepresentation(options)

  • options Object
    • scaleFactor Double - The scale factor to add the image representation for.要为其添加图像表示的比例因子。
    • width Integer (optional) - Defaults to 0. Required if a bitmap buffer is specified as buffer.默认值为0。如果位图缓冲区被指定为buffer,则为必需。
    • height Integer (optional) - Defaults to 0. Required if a bitmap buffer is specified as buffer.默认值为0。如果位图缓冲区被指定为buffer,则为必需。
    • buffer Buffer (optional) - The buffer containing the raw image data.包含原始图像数据的缓冲区。
    • dataURL string (optional) - The data URL containing either a base 64 encoded PNG or JPEG image.包含基本64编码的PNG或JPEG图像的数据URL。

Add an image representation for a specific scale factor. 添加特定比例因子的图像表示。This can be used to explicitly add different scale factor representations to an image. 这可以用于显式地向图像添加不同的比例因子表示。This can be called on empty images.这可以在空图像上调用。

Instance Properties实例属性

nativeImage.isMacTemplateImage macOS

A boolean property that determines whether the image is considered a template image.一个boolean属性,用于确定图像是否被视为模板图像

Please note that this property only has an effect on macOS.请注意,此属性仅对macOS有影响。