当前位置: 首页 > 文档资料 > Electron 中文文档 >

nativeImage

优质
小牛编辑
160浏览
2023-12-01

使用 PNG 或 JPG 文件创建托盘、dock和应用程序图标。

进程: Main, Renderer

在Electron中, 对所有创建 images 的 api 来说, 您可以传递文件路径或 NativeImage 实例。当传递 null 时, 将创建一个空的image 对象.

例如, 创建托盘或设置窗口图标时, 你可以传递 String 格式的图片路径

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

或者从剪贴板中读取返回 NativeImage 的图像:

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

Create tray, dock, and application icons using PNG or JPG files.

Process: Main, Renderer

In Electron, for the APIs that take images, you can pass either file paths or NativeImage instances. An empty image will be used when null is passed.

For example, when creating a tray or setting a window's icon, you can pass an image file path as a String:

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

Or read the image from the clipboard which returns a NativeImage:

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

支持的格式

当前支持 PNGJPEG 图像格式。建议使用 PNG, 因为它支持透明和无损压缩。

在 Windows 上, 还可以从文件路径加载 ICO 图标。为了最佳的视觉质量, 建议在中至少包括以下大小:

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

在这篇文章中查看 尺寸说明 的章节

Supported Formats

Currently PNG and JPEG image formats are supported. PNG is recommended because of its support for transparency and lossless compression.

On Windows, you can also load ICO icons from file paths. 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.

高分辨率

在具有高 DPI 支持的平台 (如 Apple 视网膜显示器) 上, 可以在图像的基本文件名之后追加 @ 2x 以将其标记为高分辨率图像。

例如, 如果 icon. png 是具有标准分辨率的普通图像, 而 icon@2x. png 将被视为具有两倍 DPI 密度的高分辨率图像。

如果希望同时支持不同 DPI 密度的显示器, 可以将不同大小的图像放在同一文件夹中, 并使用没有 DPI 后缀的文件名。例如:

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

还支持下面这些 DPI 后缀:

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

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.

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.

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. For example:

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

Following suffixes for DPI are also supported:

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

模板图片

模板图像由黑色和清晰的颜色(和一个alpha通道)组成。模板图像不能用作独立图像,通常与其他内容混合以创建所需的最终外观。

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

注意: 仅在 macOS 上支持Template image。

若要将图像标记为Template image, 其文件名应以Template 结尾。例如:

  • xxxTemplate.png
  • xxxTemplate@2x.png

Template Image

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 icon so it can adapt to both light and dark menu bars.

Note: Template image is only supported on macOS.

To mark an image as a template image, its filename should end with the word Template. For example:

  • xxxTemplate.png
  • xxxTemplate@2x.png

方法

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

Methods

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

nativeImage.createEmpty()

返回 NativeImage

创建一个空的 NativeImage 实例。

nativeImage.createEmpty()

Returns NativeImage

Creates an empty NativeImage instance.

nativeImage.createFromPath(path)

  • path String

返回 NativeImage

从位于 path 的文件创建新的 NativeImage 实例。 如果 path 不存在,,无法读取或不是有效图像,方法将返回空图像, 。

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

nativeImage.createFromPath(path)

  • path String

Returns NativeImage

Creates a new NativeImage instance from a file 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').nativeImage
let 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.

返回 NativeImage

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

nativeImage.createFromBitmap(buffer, options)

  • buffer Buffer
  • options Object

    • width Integer
    • height Integer
    • scaleFactor Double (optional) - Defaults to 1.0.

Returns NativeImage

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 Buffer
  • options Object (可选)
  • width Integer (可选) - 对于位图bitmap, 缓冲区(buffers) 是必需的
  • height Integer (可选) - 对于位图bitmap, 缓冲区(buffers) 是必需的
  • scaleFactor Double (可选) - 默认为 1.0.

返回 NativeImage

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

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.

Returns NativeImage

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

nativeImage.createFromDataURL(dataURL)

  • dataURL String

返回 NativeImage

dataURL 创建新的 NativeImage 实例。

nativeImage.createFromDataURL(dataURL)

  • dataURL String

Returns NativeImage

Creates a new NativeImage instance from dataURL.

nativeImage.createFromNamedImage(imageName[, hslShift]) macOS

  • imageName String
  • hslShift Number[]

返回 NativeImage

从映射到给定图像名称的 NSImage 创建一个 NativeImage 实例。 可以使用的值, 请参见 NSImageName 文档。

使用以下规则将hslShift应用于图像

  • 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]将使图像完全变黑.

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

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

nativeImage.createFromNamedImage(imageName[, hslShift]) macOS

  • imageName String
  • hslShift Number[]

Returns NativeImage

Creates a new NativeImage instance from the NSImage that maps to the given image name. See NSImageName for a list of possible values.

The hslShift is applied to the image with the following rules

  • 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).
  • hsl_shift[1] (saturation): A saturation shift for the image, with the following key values: 0 = remove all color. 0.5 = leave unchanged. 1 = fully saturate the image.
  • hsl_shift[2] (lightness): A lightness shift for the image, with the following key values: 0 = remove all lightness (make all pixels black). 0.5 = leave unchanged. 1 = full lightness (make all pixels white).

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

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

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

类: NativeImage

本机图像,如托盘、dock栏和应用图标。

进程: Main, Renderer

Class: NativeImage

Natively wrap images such as tray, dock, and application icons.

Process: Main, Renderer

实例方法

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

Instance Methods

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

image.toPNG([options])

  • options Object (可选)
  • scaleFactor Double (可选) - 默认值为 1.0.

返回 Buffer-一个包含图像 PNG 编码数据的 Buffer 。

image.toPNG([options])

  • options Object (optional)

    • scaleFactor Double (optional) - Defaults to 1.0.

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

image.toJPEG(quality)

  • quality Integer ( 必需 )-介于 0-100 之间。

返回 Buffer-一个包含图像 JPEG 编码数据的 Buffer 。

image.toJPEG(quality)

  • quality Integer (required) - Between 0 - 100.

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

image.toBitmap([options])

  • options Object (可选)
  • scaleFactor Double (可选) - 默认值为 1.0.

返回 Buffer-一个包含图像的原始位图像素数据副本的 Buffer 。

image.toBitmap([options])

  • options Object (optional)

    • scaleFactor Double (optional) - Defaults to 1.0.

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

image.toDataURL([options])

  • options Object (可选)
  • scaleFactor Double (可选) - 默认值为 1.0.

返回 String-图像的数据 URL。

image.toDataURL([options])

  • options Object (optional)

    • scaleFactor Double (optional) - Defaults to 1.0.

Returns String - The data URL of the image.

image.getBitmap([options])

  • options Object (可选)
  • scaleFactor Double (可选) - 默认值为 1.0.

返回 Buffer-一个包含图像原始位图像素数据的 Buffer 。

getBitmap()toBitmap() 的不同之处在于,<code>getBitmap() 不会拷贝位图数据,所以你必须在返回 Buffer 后立刻使用它,否则数据可能会被更改或销毁

image.getBitmap([options])

  • options Object (optional)

    • scaleFactor Double (optional) - Defaults to 1.0.

Returns Buffer - A Buffer that contains the image's raw bitmap pixel data.

The difference between getBitmap() and toBitmap() is, 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.

image.getNativeHandle() macOS

返回 Buffer-一个 Buffer , 它将 C 指针存储在图像的基础本机句柄上。 在 macOS 上, 将返回指向 NSImage 实例的指针。

请注意, 返回的指针是指向基础本机映像而不是副本的弱指针, 因此 必须 确保关联的 nativeImage 实例保留在周围。

image.getNativeHandle() macOS

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

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-图像是否为空。

image.isEmpty()

Returns Boolean - Whether the image is empty.

image.getSize()

Returns Size

image.getSize()

Returns Size

image.setTemplateImage(option)

  • option Boolean

将图像标记为模板图像。

image.setTemplateImage(option)

  • option Boolean

Marks the image as a template image.

image.isTemplateImage()

返回 Boolean-图像是否为模板图像。

image.isTemplateImage()

Returns Boolean - Whether the image is a template image.

image.crop(rect)

  • rect Rectangle -要裁剪的图像区域.

返回 NativeImage-裁剪的图像。

image.crop(rect)

  • rect Rectangle - The area of the image to crop.

Returns NativeImage - The cropped image.

image.resize(options)

  • optionsObject width Integer (可选)-默认为图像的宽度。 height Integer (可选) - 默认值为图片高度. * quality String (optional) 所要设置的图片质量。 支持的值为good, betterbest. 默认值为best. 这些值表示期望的 质量/速度 的权衡。 它们被翻译成一种基于算法的方法,它依赖于底层平台的能力(CPU, GPU)。 这三种方法都可以在指定的平台上映射到相同的算法。

返回 NativeImage-裁剪的图像。

如果只指定heightwidth,那么当前的长宽比将保留在缩放图像中。

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. The default is best. These 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. 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.

image.getAspectRatio()

返回 Float - 图像的长宽比.

image.getAspectRatio()

Returns Float - The image's aspect ratio.

image.addRepresentation(options)

  • options Object scaleFactor Double - 要添加图像的缩放系数. width Integer (可选) - 默认值为 0. 如果将位图缓冲区指定为buffer, 则为必填项。 height Integer (可选) - 默认值为 0. 如果将位图缓冲区指定为buffer, 则为必填项。 buffer Buffer (可选) - 包含原始图像数据的缓冲区. * dataURL String (可选) - data URL 可以为 base 64 编码的 PNG 或 JPEG 图像.

添加特定比例的图像表示。这可以明确地用来向图像添加不同的比例表示。这可以在空图像上调用。

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.
    • height Integer (optional) - Defaults to 0. Required if a bitmap buffer is specified as 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.

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.