Netpbm
Dart 的 netpbm 图像格式处理库
功能
- 创建可移植位图格式图像“P1”
- 创建可移植灰度图格式图像“P2”
- 创建可移植像素图格式图像“P3”
- 导出图像
入门
“可移植像素图格式 (PPM)、可移植灰度图格式 (PGM) 和可移植位图格式 (PBM) 是一种图像文件格式,旨在轻松地在不同平台之间交换。” – 来自维基百科
这是一种简单、人类可读的图像格式,易于初学者上手,该库允许基于像素矩阵创建图像
用法
导入
首先使用 ‘import’ 指令导入库
import 'package:netpbm/netpbm.dart';
声明图像
通过创建 ImageMono、ImageGrayscale 或 ImageColor 的实例,并指定高度和宽度来创建图像
final Image image = new ImageGrayscale(height: 10, width: 10);
操作像素值
图像自动初始化为全 0(黑色)。
通过将图像视为矩阵来添加像素值
image[5][5] = 52;
此行将值 52 分配给 x=5, y=5 处的像素
上面的行仅适用于 ImageGrayscale,其值为 ‘int’ 类型,范围在 0 到 255 之间。
ImageMono 的值要么是 true 要么是 false(白色或黑色)
final Image image = new ImageMono(height: 10, width: 10);
image[5][5] = true;
ImageColor 的值是 <Color> 类实例,它可以使用 HEX 颜色字符串初始化
final Image image = new ImageColor(height: 10, width: 10);
image[5][5] = Color('#AABBCC');
从矩阵声明图像
您还可以使用 [] 运算符声明矩阵,并使用 ‘toMatrix()’ 扩展和 .fromMatrix() 构造函数从矩阵构建图像,只要矩阵是矩形的(所有行长度相同)
final Image image = new ImageGrayscale.fromMatrix(
[
[50, 25, 0, 0],
[25, 50, 25, 0],
[0, 25, 50, 25],
[0, 0, 25, 50]
].toMatrix() //<- Transforms matrix into StaticMatrix<int>
);
StaticMatrix(或 PixelMatrix,它是别名)包含所有像素值,上面的实现仅适用于与 int 类型兼容的 ImageGrayscale。
要创建 ImageMono 矩阵,您可以创建一个包含 1 和 0 的矩阵,然后使用 .toMono() 扩展将其转换为 bool 兼容值
final Image image = new ImageMono.fromMatrix(
[
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]
].toMatrix().toMono() //<- Transform into matrix and then into StaticMatrix<bool>
);
要创建 ImageColor 矩阵,您可以通过仅创建一个包含 HEX 值的字符串矩阵然后使用 .toColorFromHex() 扩展对其进行转换来跳过颜色构造函数
final Image image = new ImageColor.fromMatrix(
[
['#FF0000', '#00FF00', '#0000FF'],
['#FFFF00', '#FF00FF', '#00FFFF']
].toMatrix().toColorFromHex()); //<- Transform into matrix and then into Colors
);
导出图像
您可以使用每个图像类型中实现的 _.toFile(filename)_ 方法导出任何图像
final Image image = new ...// Create some sort of image
...
image.toFile('my_image'); // Export image
图像扩展名会根据图像类型自动分配
附加信息
待办:读取文件
欢迎贡献并使用此库在您自己的项目中?